diff --git a/src/Control/ContentNegotiator.php b/src/Control/ContentNegotiator.php
index 21ec89f3e6b..aeb3b9f54a8 100644
--- a/src/Control/ContentNegotiator.php
+++ b/src/Control/ContentNegotiator.php
@@ -116,7 +116,7 @@ public static function setEnabled($enabled)
*/
public static function process(HTTPResponse $response)
{
- if (!self::enabled_for($response)) {
+ if (!ContentNegotiator::enabled_for($response)) {
return;
}
diff --git a/src/Control/Controller.php b/src/Control/Controller.php
index 80d7047c06c..402a9750402 100644
--- a/src/Control/Controller.php
+++ b/src/Control/Controller.php
@@ -573,7 +573,7 @@ public function pushCurrent()
{
// Ensure this controller has a valid session
$this->getRequest()->getSession();
- array_unshift(self::$controller_stack, $this);
+ array_unshift(Controller::$controller_stack, $this);
}
/**
@@ -581,8 +581,8 @@ public function pushCurrent()
*/
public function popCurrent()
{
- if ($this === self::$controller_stack[0]) {
- array_shift(self::$controller_stack);
+ if ($this === Controller::$controller_stack[0]) {
+ array_shift(Controller::$controller_stack);
} else {
$class = static::class;
user_error(
@@ -693,7 +693,7 @@ public static function normaliseTrailingSlash(string $url): string
}
// Normlise trailing slash
- $shouldHaveTrailingSlash = self::config()->uninherited('add_trailing_slash');
+ $shouldHaveTrailingSlash = static::config()->uninherited('add_trailing_slash');
if ($shouldHaveTrailingSlash
&& !str_ends_with($url, '/')
&& !preg_match('/^(.*)\.([^\/]*)$/', Director::makeRelative($url))
diff --git a/src/Control/Cookie.php b/src/Control/Cookie.php
index 2995e844f9e..2bcafa606de 100644
--- a/src/Control/Cookie.php
+++ b/src/Control/Cookie.php
@@ -31,7 +31,7 @@ class Cookie
* Must be "Strict", "Lax", or "None"
* @config
*/
- private static string $default_samesite = self::SAMESITE_LAX;
+ private static string $default_samesite = Cookie::SAMESITE_LAX;
/**
* Fetch the current instance of the cookie backend.
@@ -67,7 +67,7 @@ public static function set(
$secure = false,
$httpOnly = true
) {
- return self::get_inst()->set($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
+ return Cookie::get_inst()->set($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
}
/**
@@ -80,7 +80,7 @@ public static function set(
*/
public static function get($name, $includeUnsent = true)
{
- return self::get_inst()->get($name, $includeUnsent);
+ return Cookie::get_inst()->get($name, $includeUnsent);
}
/**
@@ -92,7 +92,7 @@ public static function get($name, $includeUnsent = true)
*/
public static function get_all($includeUnsent = true)
{
- return self::get_inst()->getAll($includeUnsent);
+ return Cookie::get_inst()->getAll($includeUnsent);
}
/**
@@ -104,7 +104,7 @@ public static function get_all($includeUnsent = true)
*/
public static function force_expiry($name, $path = null, $domain = null, $secure = false, $httpOnly = true)
{
- return self::get_inst()->forceExpiry($name, $path, $domain, $secure, $httpOnly);
+ return Cookie::get_inst()->forceExpiry($name, $path, $domain, $secure, $httpOnly);
}
/**
@@ -116,14 +116,14 @@ public static function force_expiry($name, $path = null, $domain = null, $secure
public static function validateSameSite(string $sameSite): void
{
$validValues = [
- self::SAMESITE_STRICT,
- self::SAMESITE_LAX,
- self::SAMESITE_NONE,
+ Cookie::SAMESITE_STRICT,
+ Cookie::SAMESITE_LAX,
+ Cookie::SAMESITE_NONE,
];
if (!in_array($sameSite, $validValues)) {
throw new LogicException('Cookie samesite must be "Strict", "Lax", or "None"');
}
- if ($sameSite === self::SAMESITE_NONE && !Director::is_https(self::getRequest())) {
+ if ($sameSite === Cookie::SAMESITE_NONE && !Director::is_https(Cookie::getRequest())) {
Injector::inst()->get(LoggerInterface::class)->warning('Cookie samesite cannot be "None" for non-https requests.');
}
}
diff --git a/src/Control/Director.php b/src/Control/Director.php
index f91fc93b478..8318e5dd6bb 100644
--- a/src/Control/Director.php
+++ b/src/Control/Director.php
@@ -238,7 +238,7 @@ public static function mockRequest(
// Ensure URL is properly made relative.
// Example: url passed is "/ss31/my-page" (prefixed with BASE_URL), this should be changed to "my-page"
- $url = self::makeRelative($url);
+ $url = Director::makeRelative($url);
if (strpos($url ?? '', '?') !== false) {
list($url, $getVarsEncoded) = explode('?', $url ?? '', 2);
parse_str($getVarsEncoded ?? '', $newVars['_GET']);
@@ -371,7 +371,7 @@ public function handleRequest(HTTPRequest $request)
*/
public static function get_current_page()
{
- return self::$current_page ? self::$current_page : Controller::curr();
+ return Director::$current_page ? Director::$current_page : Controller::curr();
}
/**
@@ -381,7 +381,7 @@ public static function get_current_page()
*/
public static function set_current_page($page)
{
- self::$current_page = $page;
+ Director::$current_page = $page;
}
/**
@@ -394,7 +394,7 @@ public static function set_current_page($page)
* - REQUEST - Resolve this path to the current url (i.e. behaves as though no `
'; $output .= "" . $this->formatCaller($caller) . " - \n"; if (is_string($val)) { - $output .= wordwrap($val ?? '', self::config()->columns ?? 0); + $output .= wordwrap($val ?? '', static::config()->columns ?? 0); } else { $output .= var_export($val, true); } diff --git a/src/Dev/Deprecation.php b/src/Dev/Deprecation.php index eefc1b36dab..9c7d4f5dab1 100644 --- a/src/Dev/Deprecation.php +++ b/src/Dev/Deprecation.php @@ -111,14 +111,14 @@ public static function disable(): void */ public static function withNoReplacement(callable $func) { - if (self::$insideWithNoReplacement) { + if (Deprecation::$insideWithNoReplacement) { return $func(); } - self::$insideWithNoReplacement = true; + Deprecation::$insideWithNoReplacement = true; try { return $func(); } finally { - self::$insideWithNoReplacement = false; + Deprecation::$insideWithNoReplacement = false; } } @@ -138,7 +138,7 @@ protected static function get_called_method_from_trace($backtrace, $level = 1) } $newLevel = $level; // handle closures inside withNoReplacement() - if (self::$insideWithNoReplacement + if (Deprecation::$insideWithNoReplacement && substr($backtrace[$newLevel]['function'], -strlen('{closure}')) === '{closure}' ) { $newLevel = $newLevel + 2; @@ -184,7 +184,7 @@ public static function isEnabled(): bool */ public static function isTriggeringError(): bool { - return self::$isTriggeringError; + return Deprecation::$isTriggeringError; } /** @@ -195,7 +195,7 @@ public static function isTriggeringError(): bool */ public static function setShouldShowForHttp(bool $value): void { - self::$shouldShowForHttp = $value; + Deprecation::$shouldShowForHttp = $value; } /** @@ -206,7 +206,7 @@ public static function setShouldShowForHttp(bool $value): void */ public static function setShouldShowForCli(bool $value): void { - self::$shouldShowForCli = $value; + Deprecation::$shouldShowForCli = $value; } /** @@ -217,9 +217,9 @@ public static function shouldShowForHttp(): bool { if (Environment::hasEnv('SS_DEPRECATION_SHOW_HTTP')) { $envVar = Environment::getEnv('SS_DEPRECATION_SHOW_HTTP'); - return self::varAsBoolean($envVar); + return Deprecation::varAsBoolean($envVar); } - return self::$shouldShowForHttp; + return Deprecation::$shouldShowForHttp; } /** @@ -230,34 +230,34 @@ public static function shouldShowForCli(): bool { if (Environment::hasEnv('SS_DEPRECATION_SHOW_CLI')) { $envVar = Environment::getEnv('SS_DEPRECATION_SHOW_CLI'); - return self::varAsBoolean($envVar); + return Deprecation::varAsBoolean($envVar); } - return self::$shouldShowForCli; + return Deprecation::$shouldShowForCli; } public static function outputNotices(): void { - if (!self::isEnabled()) { + if (!Deprecation::isEnabled()) { return; } $count = 0; - $origCount = count(self::$userErrorMessageBuffer); + $origCount = count(Deprecation::$userErrorMessageBuffer); while ($origCount > $count) { $count++; - $arr = array_shift(self::$userErrorMessageBuffer); + $arr = array_shift(Deprecation::$userErrorMessageBuffer); $message = $arr['message']; $calledInsideWithNoReplacement = $arr['calledInsideWithNoReplacement']; - if ($calledInsideWithNoReplacement && !self::$showNoReplacementNotices) { + if ($calledInsideWithNoReplacement && !Deprecation::$showNoReplacementNotices) { continue; } - self::$isTriggeringError = true; + Deprecation::$isTriggeringError = true; user_error($message, E_USER_DEPRECATED); - self::$isTriggeringError = false; + Deprecation::$isTriggeringError = false; } // Make absolutely sure the buffer is empty - array_shift seems to leave an item in the array // if we're not using numeric keys. - self::$userErrorMessageBuffer = []; + Deprecation::$userErrorMessageBuffer = []; } /** @@ -278,17 +278,17 @@ public static function notice($atVersion, $string = '', $scope = Deprecation::SC // calls something else that calls Deprecation::notice() try { $data = null; - if ($scope === self::SCOPE_CONFIG) { + if ($scope === Deprecation::SCOPE_CONFIG) { // 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 $data = [ 'key' => sha1($string), 'message' => $string, - 'calledInsideWithNoReplacement' => self::$insideWithNoReplacement + 'calledInsideWithNoReplacement' => Deprecation::$insideWithNoReplacement ]; } else { - if (!self::isEnabled()) { - // Do not add to self::$userErrorMessageBuffer, as the backtrace is too expensive + if (!Deprecation::isEnabled()) { + // Do not add to Deprecation::$userErrorMessageBuffer, as the backtrace is too expensive return; } @@ -298,7 +298,7 @@ public static function notice($atVersion, $string = '', $scope = Deprecation::SC // Get the calling scope if ($scope == Deprecation::SCOPE_METHOD) { $backtrace = debug_backtrace(0); - $caller = self::get_called_method_from_trace($backtrace, 1); + $caller = Deprecation::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)'; @@ -310,8 +310,8 @@ public static function notice($atVersion, $string = '', $scope = Deprecation::SC $string .= "."; } - $level = self::$insideWithNoReplacement ? 4 : 2; - $string .= " Called from " . self::get_called_method_from_trace($backtrace, $level) . '.'; + $level = Deprecation::$insideWithNoReplacement ? 4 : 2; + $string .= " Called from " . Deprecation::get_called_method_from_trace($backtrace, $level) . '.'; if ($caller) { $string = $caller . ' is deprecated.' . ($string ? ' ' . $string : ''); @@ -319,22 +319,22 @@ public static function notice($atVersion, $string = '', $scope = Deprecation::SC $data = [ 'key' => sha1($string), 'message' => $string, - 'calledInsideWithNoReplacement' => self::$insideWithNoReplacement + 'calledInsideWithNoReplacement' => Deprecation::$insideWithNoReplacement ]; } - if ($data && !array_key_exists($data['key'], self::$userErrorMessageBuffer)) { + if ($data && !array_key_exists($data['key'], Deprecation::$userErrorMessageBuffer)) { // Store de-duplicated data in a buffer to be outputted when outputNotices() is called - self::$userErrorMessageBuffer[$data['key']] = $data; + Deprecation::$userErrorMessageBuffer[$data['key']] = $data; // 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 - if (!self::$haveSetShutdownFunction && self::isEnabled()) { + if (!Deprecation::$haveSetShutdownFunction && Deprecation::isEnabled()) { register_shutdown_function(function () { - self::outputNotices(); + Deprecation::outputNotices(); }); - self::$haveSetShutdownFunction = true; + Deprecation::$haveSetShutdownFunction = true; } } } catch (BadMethodCallException $e) { diff --git a/src/Dev/Install/DatabaseAdapterRegistry.php b/src/Dev/Install/DatabaseAdapterRegistry.php index 0a77da8075e..4607e44720b 100644 --- a/src/Dev/Install/DatabaseAdapterRegistry.php +++ b/src/Dev/Install/DatabaseAdapterRegistry.php @@ -96,10 +96,10 @@ public static function register($config) // set default fields if none are defined already if (!isset($config['fields'])) { - $config['fields'] = self::$default_fields; + $config['fields'] = DatabaseAdapterRegistry::$default_fields; } - self::$adapters[$config['class']] = $config; + DatabaseAdapterRegistry::$adapters[$config['class']] = $config; } /** @@ -109,7 +109,7 @@ public static function register($config) */ public static function unregister($class) { - unset(self::$adapters[$class]); + unset(DatabaseAdapterRegistry::$adapters[$class]); } /** @@ -204,7 +204,7 @@ public static function flush() */ public static function get_adapters() { - return self::$adapters; + return DatabaseAdapterRegistry::$adapters; } /** @@ -215,8 +215,8 @@ public static function get_adapters() */ public static function get_adapter($class) { - if (isset(self::$adapters[$class])) { - return self::$adapters[$class]; + if (isset(DatabaseAdapterRegistry::$adapters[$class])) { + return DatabaseAdapterRegistry::$adapters[$class]; } return null; } @@ -228,7 +228,7 @@ public static function get_adapter($class) */ public static function get_default_fields() { - return self::$default_fields; + return DatabaseAdapterRegistry::$default_fields; } /** diff --git a/src/Dev/SapphireTest.php b/src/Dev/SapphireTest.php index 3694f18ae42..303c22a92d0 100644 --- a/src/Dev/SapphireTest.php +++ b/src/Dev/SapphireTest.php @@ -206,7 +206,7 @@ public static function getRequiredExtensions() */ protected static function is_running_test() { - return self::$is_running_test; + return SapphireTest::$is_running_test; } /** @@ -216,7 +216,7 @@ protected static function is_running_test() */ protected static function set_is_running_test($bool) { - self::$is_running_test = $bool; + SapphireTest::$is_running_test = $bool; } /** @@ -653,7 +653,7 @@ public static function assertEmailSent($to, $from = null, $subject = null, $cont public static function assertListContains($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -691,7 +691,7 @@ public static function assertListContains($matches, SS_List $list, $message = '' public static function assertListNotContains($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -731,7 +731,7 @@ public static function assertListNotContains($matches, SS_List $list, $message = public static function assertListEquals($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -762,7 +762,7 @@ public static function assertListEquals($matches, SS_List $list, $message = '') public static function assertListAllMatch($match, SS_List $list, $message = '') { if (!is_array($match)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); diff --git a/src/Dev/TestKernel.php b/src/Dev/TestKernel.php index 67229f5cae1..2e501b150eb 100644 --- a/src/Dev/TestKernel.php +++ b/src/Dev/TestKernel.php @@ -11,7 +11,7 @@ class TestKernel extends CoreKernel { public function __construct($basePath) { - $this->setEnvironment(self::DEV); + $this->setEnvironment(TestKernel::DEV); parent::__construct($basePath); } @@ -23,7 +23,7 @@ public function __construct($basePath) */ public function reset() { - $this->setEnvironment(self::DEV); + $this->setEnvironment(TestKernel::DEV); $this->bootPHP(); return $this; } diff --git a/src/Dev/Validation/RelationValidationService.php b/src/Dev/Validation/RelationValidationService.php index 0b85bbbbf61..2b1b7e7201c 100644 --- a/src/Dev/Validation/RelationValidationService.php +++ b/src/Dev/Validation/RelationValidationService.php @@ -82,7 +82,7 @@ public function clearErrors(): void public static function reset(): void { - $service = self::singleton(); + $service = RelationValidationService::singleton(); $service->clearErrors(); $service->ignoreConfig = false; } @@ -98,7 +98,7 @@ public static function reset(): void */ public function validateRelations(): array { - self::reset(); + RelationValidationService::reset(); $classes = ClassInfo::subclassesFor(DataObject::class); return $this->validateClasses($classes); @@ -139,7 +139,7 @@ public function executeValidation(): void */ public function inspectClasses(array $classes): array { - self::reset(); + RelationValidationService::reset(); $this->ignoreConfig = true; return $this->validateClasses($classes); diff --git a/src/Forms/ConfirmedPasswordField.php b/src/Forms/ConfirmedPasswordField.php index bdabb9beaba..fa61dc91a38 100644 --- a/src/Forms/ConfirmedPasswordField.php +++ b/src/Forms/ConfirmedPasswordField.php @@ -48,7 +48,7 @@ class ConfirmedPasswordField extends FormField /** * Allow empty fields when entering the password for the first time * If this is set to true then a random password may be generated if the field is empty - * depending on the value of $self::generateRandomPasswordOnEmtpy + * depending on the value of $ConfirmedPasswordField::generateRandomPasswordOnEmtpy * * @var boolean */ diff --git a/src/Forms/Form.php b/src/Forms/Form.php index 111bbf1203e..69151c12145 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -278,7 +278,7 @@ class Form extends ViewableData implements HasRequestHandler */ public function __construct( RequestHandler $controller = null, - $name = self::DEFAULT_NAME, + $name = Form::DEFAULT_NAME, FieldList $fields = null, FieldList $actions = null, Validator $validator = null @@ -348,7 +348,7 @@ public function restoreFormState() // load data in from previous submission upon error $data = $this->getSessionData(); if (isset($data)) { - $this->loadDataFrom($data, self::MERGE_AS_INTERNAL_VALUE); + $this->loadDataFrom($data, Form::MERGE_AS_INTERNAL_VALUE); } return $this; } @@ -536,7 +536,7 @@ public function castingHelper($field) */ protected function setupDefaultClasses() { - $defaultClasses = self::config()->get('default_classes'); + $defaultClasses = static::config()->get('default_classes'); if ($defaultClasses) { foreach ($defaultClasses as $class) { $this->addExtraClass($class); @@ -560,7 +560,7 @@ public function getValidationResponseCallback() * in which case the default form behaviour will kick in. * * @param $callback - * @return self + * @return Form */ public function setValidationResponseCallback($callback) { @@ -954,12 +954,12 @@ public function getEncType() if ($fields = $this->fields->dataFields()) { foreach ($fields as $field) { if ($field instanceof FileField) { - return self::ENC_TYPE_MULTIPART; + return Form::ENC_TYPE_MULTIPART; } } } - return self::ENC_TYPE_URLENCODED; + return Form::ENC_TYPE_URLENCODED; } /** @@ -1343,7 +1343,7 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null) // Handle the backwards compatible case of passing "true" as the second argument if ($mergeStrategy === true) { - $mergeStrategy = self::MERGE_CLEAR_MISSING; + $mergeStrategy = Form::MERGE_CLEAR_MISSING; } elseif ($mergeStrategy === false) { $mergeStrategy = 0; } @@ -1359,9 +1359,9 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null) // Using the `MERGE_AS_INTERNAL_VALUE` or `MERGE_AS_SUBMITTED_VALUE` flags users can explicitly specify which // `setValue` method to use. - if (($mergeStrategy & self::MERGE_AS_INTERNAL_VALUE) == self::MERGE_AS_INTERNAL_VALUE) { + if (($mergeStrategy & Form::MERGE_AS_INTERNAL_VALUE) == Form::MERGE_AS_INTERNAL_VALUE) { $submitted = false; - } elseif (($mergeStrategy & self::MERGE_AS_SUBMITTED_VALUE) == self::MERGE_AS_SUBMITTED_VALUE) { + } elseif (($mergeStrategy & Form::MERGE_AS_SUBMITTED_VALUE) == Form::MERGE_AS_SUBMITTED_VALUE) { $submitted = true; } @@ -1455,10 +1455,10 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null) // save to the field if either a value is given, or loading of blank/undefined values is forced $setValue = false; if ($exists) { - if ($val != false || ($mergeStrategy & self::MERGE_IGNORE_FALSEISH) != self::MERGE_IGNORE_FALSEISH) { + if ($val != false || ($mergeStrategy & Form::MERGE_IGNORE_FALSEISH) != Form::MERGE_IGNORE_FALSEISH) { $setValue = true; } - } elseif (($mergeStrategy & self::MERGE_CLEAR_MISSING) == self::MERGE_CLEAR_MISSING) { + } elseif (($mergeStrategy & Form::MERGE_CLEAR_MISSING) == Form::MERGE_CLEAR_MISSING) { $setValue = true; } diff --git a/src/Forms/FormFactory.php b/src/Forms/FormFactory.php index 7571418ba98..b900fbcd2fd 100644 --- a/src/Forms/FormFactory.php +++ b/src/Forms/FormFactory.php @@ -25,7 +25,7 @@ interface FormFactory * Custom factories may support more advanced parameters. * @return Form */ - public function getForm(RequestHandler $controller = null, $name = self::DEFAULT_NAME, $context = []); + public function getForm(RequestHandler $controller = null, $name = FormFactory::DEFAULT_NAME, $context = []); /** * Return list of mandatory context keys diff --git a/src/Forms/FormField.php b/src/Forms/FormField.php index c6a56ece7e6..77a46ef2c18 100644 --- a/src/Forms/FormField.php +++ b/src/Forms/FormField.php @@ -238,7 +238,7 @@ class FormField extends RequestHandler * or simply be a block of stand-alone content. As with 'Custom', * the component property is mandatory if this is assigned. * - * Each value has an equivalent constant, e.g. {@link self::SCHEMA_DATA_TYPE_STRING}. + * Each value has an equivalent constant, e.g. {@link FormField::SCHEMA_DATA_TYPE_STRING}. * * @var string */ @@ -333,7 +333,7 @@ public function __construct($name, $title = null, $value = null) $this->setName($name); if ($title === null) { - $this->title = self::name_to_label($name); + $this->title = FormField::name_to_label($name); } else { $this->title = $title; } @@ -1566,7 +1566,7 @@ public function getTitleTip(): ?Tip * @param Tip|null $tip * @return $this */ - public function setTitleTip(?Tip $tip): self + public function setTitleTip(?Tip $tip): FormField { $this->titleTip = $tip; return $this; diff --git a/src/Forms/GridField/GridField.php b/src/Forms/GridField/GridField.php index d42fb7b34e9..5908b95aae6 100644 --- a/src/Forms/GridField/GridField.php +++ b/src/Forms/GridField/GridField.php @@ -558,11 +558,11 @@ public function FieldHolder($properties = []) // Continue looping if any placeholders exist while (array_filter($content ?? [], function ($value) { - return preg_match(self::FRAGMENT_REGEX ?? '', $value ?? ''); + return preg_match(GridField::FRAGMENT_REGEX ?? '', $value ?? ''); })) { foreach ($content as $contentKey => $contentValue) { // Skip if this specific content has no placeholders - if (!preg_match_all(self::FRAGMENT_REGEX ?? '', $contentValue ?? '', $matches)) { + if (!preg_match_all(GridField::FRAGMENT_REGEX ?? '', $contentValue ?? '', $matches)) { continue; } foreach ($matches[1] as $match) { @@ -578,7 +578,7 @@ public function FieldHolder($properties = []) // If the fragment still has a fragment definition in it, when we should defer // this item until later. - if (preg_match(self::FRAGMENT_REGEX ?? '', $fragment ?? '', $matches)) { + if (preg_match(GridField::FRAGMENT_REGEX ?? '', $fragment ?? '', $matches)) { if (isset($fragmentDeferred[$contentKey]) && $fragmentDeferred[$contentKey] > 5) { throw new LogicException(sprintf( 'GridField HTML fragment "%s" and "%s" appear to have a circular dependency.', diff --git a/src/Forms/GridField/GridFieldDetailForm.php b/src/Forms/GridField/GridFieldDetailForm.php index 07299cc93fd..e776f333daa 100644 --- a/src/Forms/GridField/GridFieldDetailForm.php +++ b/src/Forms/GridField/GridFieldDetailForm.php @@ -285,7 +285,7 @@ public function getName() * database, and the record has a CMSEditLink method, then the system will redirect to the * URL returned by that method. */ - public function setRedirectMissingRecords(bool $redirectMissingRecords): self + public function setRedirectMissingRecords(bool $redirectMissingRecords): GridFieldDetailForm { $this->redirectMissingRecords = $redirectMissingRecords; return $this; diff --git a/src/Forms/GridField/GridFieldFilterHeader.php b/src/Forms/GridField/GridFieldFilterHeader.php index 1fb47d2499d..2e96e28f889 100755 --- a/src/Forms/GridField/GridFieldFilterHeader.php +++ b/src/Forms/GridField/GridFieldFilterHeader.php @@ -92,7 +92,7 @@ public function getSearchField(): ?string return $this->searchField; } - public function setSearchField(string $field): self + public function setSearchField(string $field): GridFieldFilterHeader { $this->searchField = $field; return $this; diff --git a/src/Forms/GridField/GridState_Data.php b/src/Forms/GridField/GridState_Data.php index 2bbc7d791f4..f74c60a2377 100644 --- a/src/Forms/GridField/GridState_Data.php +++ b/src/Forms/GridField/GridState_Data.php @@ -25,14 +25,14 @@ public function __construct($data = []) public function __get($name) { - return $this->getData($name, new self()); + return $this->getData($name, new GridState_Data()); } public function __call($name, $arguments) { // Assume first parameter is default value if (empty($arguments)) { - $default = new self(); + $default = new GridState_Data(); } else { $default = $arguments[0]; } @@ -72,7 +72,7 @@ public function getData($name, $default = null) $this->data[$name] = $default; } else { if (is_array($this->data[$name])) { - $this->data[$name] = new self($this->data[$name]); + $this->data[$name] = new GridState_Data($this->data[$name]); } } diff --git a/src/Forms/HTMLEditor/HTMLEditorConfig.php b/src/Forms/HTMLEditor/HTMLEditorConfig.php index 824d11f73c7..6c685bf29c5 100644 --- a/src/Forms/HTMLEditor/HTMLEditorConfig.php +++ b/src/Forms/HTMLEditor/HTMLEditorConfig.php @@ -81,11 +81,11 @@ public static function get($identifier = null) return static::get_active(); } // Create new instance if unconfigured - if (!isset(self::$configs[$identifier])) { - self::$configs[$identifier] = static::create(); - self::$configs[$identifier]->setOption('editorIdentifier', $identifier); + if (!isset(HTMLEditorConfig::$configs[$identifier])) { + HTMLEditorConfig::$configs[$identifier] = static::create(); + HTMLEditorConfig::$configs[$identifier]->setOption('editorIdentifier', $identifier); } - return self::$configs[$identifier]; + return HTMLEditorConfig::$configs[$identifier]; } /** @@ -98,10 +98,10 @@ public static function get($identifier = null) public static function set_config($identifier, HTMLEditorConfig $config = null) { if ($config) { - self::$configs[$identifier] = $config; - self::$configs[$identifier]->setOption('editorIdentifier', $identifier); + HTMLEditorConfig::$configs[$identifier] = $config; + HTMLEditorConfig::$configs[$identifier]->setOption('editorIdentifier', $identifier); } else { - unset(self::$configs[$identifier]); + unset(HTMLEditorConfig::$configs[$identifier]); } return $config; } @@ -136,7 +136,7 @@ public static function setThemes($themes) */ public static function set_active_identifier($identifier) { - self::$current = $identifier; + HTMLEditorConfig::$current = $identifier; } /** @@ -147,7 +147,7 @@ public static function set_active_identifier($identifier) */ public static function get_active_identifier() { - $identifier = self::$current ?: static::config()->get('default_config'); + $identifier = HTMLEditorConfig::$current ?: static::config()->get('default_config'); return $identifier; } @@ -158,8 +158,8 @@ public static function get_active_identifier() */ public static function get_active() { - $identifier = self::get_active_identifier(); - return self::get($identifier); + $identifier = HTMLEditorConfig::get_active_identifier(); + return HTMLEditorConfig::get($identifier); } /** @@ -184,7 +184,7 @@ public static function get_available_configs_map() { $configs = []; - foreach (self::$configs as $identifier => $config) { + foreach (HTMLEditorConfig::$configs as $identifier => $config) { $configs[$identifier] = $config->getOption('friendly_name'); } diff --git a/src/Forms/HTMLEditor/TinyMCEConfig.php b/src/Forms/HTMLEditor/TinyMCEConfig.php index 80621abd086..20c9fad9375 100644 --- a/src/Forms/HTMLEditor/TinyMCEConfig.php +++ b/src/Forms/HTMLEditor/TinyMCEConfig.php @@ -721,7 +721,7 @@ protected function getConfig() private function initImageSizePresets(array &$settings): void { if (empty($settings['image_size_presets'])) { - $settings['image_size_presets'] = self::config()->get('image_size_presets'); + $settings['image_size_presets'] = static::config()->get('image_size_presets'); } foreach ($settings['image_size_presets'] as &$preset) { @@ -736,7 +736,7 @@ private function initImageSizePresets(array &$settings): void ); } elseif (empty($preset['text']) && isset($preset['width'])) { $preset['text'] = _t( - self::class . '.PIXEL_WIDTH', + TinyMCEConfig::class . '.PIXEL_WIDTH', '{width} pixels', $preset ); @@ -926,7 +926,7 @@ public function getTinyMCEResource() * @param string $folderName * @return $this */ - public function setFolderName(string $folderName): self + public function setFolderName(string $folderName): TinyMCEConfig { $folder = Folder::find_or_make($folderName); $folderID = $folder ? $folder->ID : null; @@ -937,9 +937,9 @@ public function setFolderName(string $folderName): self public function provideI18nEntities() { $entities = [ - self::class . '.PIXEL_WIDTH' => '{width} pixels', + TinyMCEConfig::class . '.PIXEL_WIDTH' => '{width} pixels', ]; - foreach (self::config()->get('image_size_presets') as $preset) { + foreach (static::config()->get('image_size_presets') as $preset) { if (empty($preset['i18n']) || empty($preset['text'])) { continue; } diff --git a/src/Forms/HTMLReadonlyField.php b/src/Forms/HTMLReadonlyField.php index 8a028726d5e..64bb339e30f 100644 --- a/src/Forms/HTMLReadonlyField.php +++ b/src/Forms/HTMLReadonlyField.php @@ -14,7 +14,7 @@ class HTMLReadonlyField extends ReadonlyField 'ValueEntities' => 'HTMLFragment', ]; - protected $schemaDataType = self::SCHEMA_DATA_TYPE_STRUCTURAL; + protected $schemaDataType = HTMLReadonlyField::SCHEMA_DATA_TYPE_STRUCTURAL; /** * @var string diff --git a/src/Forms/HeaderField.php b/src/Forms/HeaderField.php index 610f6d82d05..fa574c43935 100644 --- a/src/Forms/HeaderField.php +++ b/src/Forms/HeaderField.php @@ -17,7 +17,7 @@ class HeaderField extends DatalessField */ protected $headingLevel = 2; - protected $schemaDataType = self::SCHEMA_DATA_TYPE_STRUCTURAL; + protected $schemaDataType = HeaderField::SCHEMA_DATA_TYPE_STRUCTURAL; /** * @var string diff --git a/src/Forms/LiteralField.php b/src/Forms/LiteralField.php index 178cd1f093f..d90b02a3c2d 100644 --- a/src/Forms/LiteralField.php +++ b/src/Forms/LiteralField.php @@ -26,7 +26,7 @@ class LiteralField extends DatalessField */ protected $content; - protected $schemaDataType = self::SCHEMA_DATA_TYPE_STRUCTURAL; + protected $schemaDataType = LiteralField::SCHEMA_DATA_TYPE_STRUCTURAL; /** * @var string diff --git a/src/Forms/SingleSelectField.php b/src/Forms/SingleSelectField.php index b3a97be5eea..1dcd6b502ed 100644 --- a/src/Forms/SingleSelectField.php +++ b/src/Forms/SingleSelectField.php @@ -67,7 +67,7 @@ public function getDefaultValue() /** * @param boolean $bool - * @return self Self reference + * @return SingleSelectField Self reference */ public function setHasEmptyDefault($bool) { diff --git a/src/Forms/TextField.php b/src/Forms/TextField.php index 4247afa6b67..49aa40b2c14 100644 --- a/src/Forms/TextField.php +++ b/src/Forms/TextField.php @@ -78,7 +78,7 @@ public function getTip(): ?Tip * @param Tip|null $tip The Tip to apply, or null to remove an existing one * @return $this */ - public function setTip(?Tip $tip = null): self + public function setTip(?Tip $tip = null): TextField { $this->tip = $tip; diff --git a/src/Forms/Tip.php b/src/Forms/Tip.php index 79b6254580b..57e43aeb6a1 100644 --- a/src/Forms/Tip.php +++ b/src/Forms/Tip.php @@ -21,7 +21,7 @@ class Tip private const DEFAULT_ICON = 'lamp'; - private const DEFAULT_IMPORTANCE_LEVEL = self::IMPORTANCE_LEVELS['NORMAL']; + private const DEFAULT_IMPORTANCE_LEVEL = Tip::IMPORTANCE_LEVELS['NORMAL']; /** * @var string The icon that should be used on the Tip button @@ -46,8 +46,8 @@ class Tip */ public function __construct( string $message, - string $importance_level = self::DEFAULT_IMPORTANCE_LEVEL, - string $icon = self::DEFAULT_ICON + string $importance_level = Tip::DEFAULT_IMPORTANCE_LEVEL, + string $icon = Tip::DEFAULT_ICON ) { $this->setMessage($message); $this->setIcon($icon); @@ -81,9 +81,9 @@ public function getImportanceLevel(): string * @return Tip * @throws InvalidArgumentException */ - public function setImportanceLevel(string $importance_level): self + public function setImportanceLevel(string $importance_level): Tip { - if (!in_array($importance_level, self::IMPORTANCE_LEVELS ?? [])) { + if (!in_array($importance_level, Tip::IMPORTANCE_LEVELS ?? [])) { throw new InvalidArgumentException( 'Provided importance level must be defined in Tip::IMPORTANCE_LEVELS' ); @@ -106,7 +106,7 @@ public function getIcon(): string * @param string $icon * @return Tip */ - public function setIcon(string $icon): self + public function setIcon(string $icon): Tip { $this->icon = $icon; @@ -125,7 +125,7 @@ public function getMessage(): string * @param string $message * @return Tip */ - public function setMessage(string $message): self + public function setMessage(string $message): Tip { $this->message = $message; diff --git a/src/Forms/TreeDropdownField.php b/src/Forms/TreeDropdownField.php index b2f9952c9c1..c503c591aa3 100644 --- a/src/Forms/TreeDropdownField.php +++ b/src/Forms/TreeDropdownField.php @@ -57,7 +57,7 @@ */ class TreeDropdownField extends FormField implements HasOneRelationFieldInterface { - protected $schemaDataType = self::SCHEMA_DATA_TYPE_SINGLESELECT; + protected $schemaDataType = TreeDropdownField::SCHEMA_DATA_TYPE_SINGLESELECT; protected $schemaComponent = 'TreeDropdownField'; @@ -561,7 +561,7 @@ public function tree(HTTPRequest $request) } else { // Return basic html $html = $markingSet->renderChildren( - [self::class . '_HTML', 'type' => 'Includes'], + [TreeDropdownField::class . '_HTML', 'type' => 'Includes'], $customised ); return HTTPResponse::create() @@ -894,10 +894,10 @@ public function getSchemaStateDefaults() protected function getCacheKey() { $target = $this->getSourceObject(); - if (!isset(self::$cacheKeyCache[$target])) { - self::$cacheKeyCache[$target] = DataList::create($target)->max('LastEdited'); + if (!isset(TreeDropdownField::$cacheKeyCache[$target])) { + TreeDropdownField::$cacheKeyCache[$target] = DataList::create($target)->max('LastEdited'); } - return self::$cacheKeyCache[$target]; + return TreeDropdownField::$cacheKeyCache[$target]; } public function getSchemaDataDefaults() @@ -917,7 +917,7 @@ public function getSchemaDataDefaults() /** * @param boolean $bool - * @return self Self reference + * @return TreeDropdownField Self reference */ public function setHasEmptyDefault($bool) { diff --git a/src/ORM/ArrayLib.php b/src/ORM/ArrayLib.php index 5a03fabee8d..371d0f6dfca 100644 --- a/src/ORM/ArrayLib.php +++ b/src/ORM/ArrayLib.php @@ -82,7 +82,7 @@ public static function valuekey($arr) */ public static function array_values_recursive($array) { - return self::flatten($array, false); + return ArrayLib::flatten($array, false); } /** @@ -146,7 +146,7 @@ public static function in_array_recursive($needle, $haystack, $strict = false) return true; } else { foreach ($haystack as $obj) { - if (self::in_array_recursive($needle, $obj, $strict)) { + if (ArrayLib::in_array_recursive($needle, $obj, $strict)) { return true; } } diff --git a/src/ORM/Connect/DBQueryBuilder.php b/src/ORM/Connect/DBQueryBuilder.php index 6a05b41d681..e94c48235d4 100644 --- a/src/ORM/Connect/DBQueryBuilder.php +++ b/src/ORM/Connect/DBQueryBuilder.php @@ -98,7 +98,7 @@ protected function buildTraceComment(): string // Skip items in the stack trace that originate from these classes or their subclasses, // we want to know what called these instead $baseClasses = [ - self::class, + DBQueryBuilder::class, DataQuery::class, SQLExpression::class, DB::class, diff --git a/src/ORM/Connect/Database.php b/src/ORM/Connect/Database.php index 183aef2a750..6b7dc9c0129 100644 --- a/src/ORM/Connect/Database.php +++ b/src/ORM/Connect/Database.php @@ -234,9 +234,9 @@ protected function benchmarkQuery($sql, $callback, $parameters = []) $sql = DB::inline_parameters($sql, $parameters); } elseif (strtolower($_REQUEST['showqueries'] ?? '') === 'whitelist') { $displaySql = false; - foreach (self::$whitelist_array as $query => $searchType) { - $fullQuery = ($searchType === self::FULL_QUERY && $query === $sql); - $partialQuery = ($searchType === self::PARTIAL_QUERY && mb_strpos($sql ?? '', $query ?? '') !== false); + foreach (Database::$whitelist_array as $query => $searchType) { + $fullQuery = ($searchType === Database::FULL_QUERY && $query === $sql); + $partialQuery = ($searchType === Database::PARTIAL_QUERY && mb_strpos($sql ?? '', $query ?? '') !== false); if (!$fullQuery && !$partialQuery) { continue; } @@ -277,7 +277,7 @@ protected function displayQuery($query, $endtime) */ public static function setWhitelistQueryArray($whitelistArray) { - self::$whitelist_array = $whitelistArray; + Database::$whitelist_array = $whitelistArray; } /** @@ -287,7 +287,7 @@ public static function setWhitelistQueryArray($whitelistArray) */ public static function getWhitelistQueryArray() { - return self::$whitelist_array; + return Database::$whitelist_array; } /** diff --git a/src/ORM/Connect/MySQLQueryBuilder.php b/src/ORM/Connect/MySQLQueryBuilder.php index 755304287d0..dfea806a2cc 100644 --- a/src/ORM/Connect/MySQLQueryBuilder.php +++ b/src/ORM/Connect/MySQLQueryBuilder.php @@ -47,7 +47,7 @@ public function buildLimitFragment(SQLSelect $query, array &$parameters) } if ($limit['limit'] === null) { - $limit['limit'] = self::MAX_ROWS; + $limit['limit'] = MySQLQueryBuilder::MAX_ROWS; } // Format the array limit, given an optional start key diff --git a/src/ORM/Connect/MySQLSchemaManager.php b/src/ORM/Connect/MySQLSchemaManager.php index bcab1341368..a4e3cafa8af 100644 --- a/src/ORM/Connect/MySQLSchemaManager.php +++ b/src/ORM/Connect/MySQLSchemaManager.php @@ -23,8 +23,8 @@ public function createTable($table, $fields = null, $indexes = null, $options = { $fieldSchemas = $indexSchemas = ""; - if (!empty($options[self::ID])) { - $addOptions = $options[self::ID]; + if (!empty($options[MySQLSchemaManager::ID])) { + $addOptions = $options[MySQLSchemaManager::ID]; } else { $addOptions = "ENGINE=InnoDB"; } @@ -97,7 +97,7 @@ public function alterTable( } } - $dbID = self::ID; + $dbID = MySQLSchemaManager::ID; if ($alteredOptions && isset($alteredOptions[$dbID])) { $this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[$dbID])); $this->alterationMessage( @@ -232,7 +232,7 @@ private function shouldUseIntegerWidth() // MySQL 8.0.17 stopped reporting the width attribute for integers // https://github.com/silverstripe/silverstripe-framework/issues/9453 // Note: MariaDB did not change its behaviour - $forceWidth = Config::inst()->get(self::class, 'schema_use_int_width'); + $forceWidth = Config::inst()->get(MySQLSchemaManager::class, 'schema_use_int_width'); if ($forceWidth !== null) { return $forceWidth; } @@ -256,11 +256,11 @@ public function fieldList($table) if ($field['Collation'] && $field['Collation'] != 'NULL') { // Cache collation info to cut down on database traffic - if (!isset(self::$_cache_collation_info[$field['Collation']])) { - self::$_cache_collation_info[$field['Collation']] + if (!isset(MySQLSchemaManager::$_cache_collation_info[$field['Collation']])) { + MySQLSchemaManager::$_cache_collation_info[$field['Collation']] = $this->query("SHOW COLLATION LIKE '{$field['Collation']}'")->record(); } - $collInfo = self::$_cache_collation_info[$field['Collation']]; + $collInfo = MySQLSchemaManager::$_cache_collation_info[$field['Collation']]; $fieldSpec .= " character set $collInfo[Charset] collate $field[Collation]"; } diff --git a/src/ORM/Connect/MySQLiConnector.php b/src/ORM/Connect/MySQLiConnector.php index ca6cad20c46..2fbbd70c5d1 100644 --- a/src/ORM/Connect/MySQLiConnector.php +++ b/src/ORM/Connect/MySQLiConnector.php @@ -108,7 +108,7 @@ public function connect($parameters, $selectDB = false) dirname($parameters['ssl_ca'] ?? ''), array_key_exists('ssl_cipher', $parameters ?? []) ? $parameters['ssl_cipher'] - : self::config()->get('ssl_cipher_default') + : static::config()->get('ssl_cipher_default') ); } diff --git a/src/ORM/Connect/NullDatabase.php b/src/ORM/Connect/NullDatabase.php index 70e5d127787..214998c37e3 100644 --- a/src/ORM/Connect/NullDatabase.php +++ b/src/ORM/Connect/NullDatabase.php @@ -34,7 +34,7 @@ class NullDatabase extends Database /** * @param string $msg */ - public function setErrorMessage(string $msg): self + public function setErrorMessage(string $msg): NullDatabase { $this->errorMessage = $msg; return $this; @@ -43,7 +43,7 @@ public function setErrorMessage(string $msg): self /** * @param string $msg */ - public function setQueryErrorMessage(string $msg): self + public function setQueryErrorMessage(string $msg): NullDatabase { $this->queryErrorMessage = $msg; return $this; diff --git a/src/ORM/DB.php b/src/ORM/DB.php index 7be15a65c7c..054b858d02f 100644 --- a/src/ORM/DB.php +++ b/src/ORM/DB.php @@ -84,7 +84,7 @@ class DB */ public static function set_conn(Database $connection, $name = 'default') { - self::$connections[$name] = $connection; + DB::$connections[$name] = $connection; } /** @@ -96,8 +96,8 @@ public static function set_conn(Database $connection, $name = 'default') */ public static function get_conn($name = 'default') { - if (isset(self::$connections[$name])) { - return self::$connections[$name]; + if (isset(DB::$connections[$name])) { + return DB::$connections[$name]; } // lazy connect @@ -118,7 +118,7 @@ public static function get_conn($name = 'default') */ public static function get_schema($name = 'default') { - $connection = self::get_conn($name); + $connection = DB::get_conn($name); if ($connection) { return $connection->getSchemaManager(); } @@ -136,7 +136,7 @@ public static function get_schema($name = 'default') */ public static function build_sql(SQLExpression $expression, &$parameters, $name = 'default') { - $connection = self::get_conn($name); + $connection = DB::get_conn($name); if ($connection) { return $connection->getQueryBuilder()->buildSQL($expression, $parameters); } else { @@ -154,7 +154,7 @@ public static function build_sql(SQLExpression $expression, &$parameters, $name */ public static function get_connector($name = 'default') { - $connection = self::get_conn($name); + $connection = DB::get_conn($name); if ($connection) { return $connection->getConnector(); } @@ -187,7 +187,7 @@ public static function set_alternative_database_name($name = null) return; } // Validate name - if ($name && !self::valid_alternative_database_name($name)) { + if ($name && !DB::valid_alternative_database_name($name)) { throw new InvalidArgumentException(sprintf( 'Invalid alternative database name: "%s"', $name @@ -200,9 +200,9 @@ public static function set_alternative_database_name($name = null) } $request = Injector::inst()->get(HTTPRequest::class); if ($name) { - $request->getSession()->set(self::ALT_DB_KEY, $name); + $request->getSession()->set(DB::ALT_DB_KEY, $name); } else { - $request->getSession()->clear(self::ALT_DB_KEY); + $request->getSession()->clear(DB::ALT_DB_KEY); } } @@ -231,8 +231,8 @@ public static function get_alternative_database_name() return null; } - $name = $request->getSession()->get(self::ALT_DB_KEY); - if (self::valid_alternative_database_name($name)) { + $name = $request->getSession()->get(DB::ALT_DB_KEY); + if (DB::valid_alternative_database_name($name)) { return $name; } @@ -271,7 +271,7 @@ public static function valid_alternative_database_name($name) public static function connect($databaseConfig, $label = 'default') { // This is used by the "testsession" module to test up a test session using an alternative name - if ($name = self::get_alternative_database_name()) { + if ($name = DB::get_alternative_database_name()) { $databaseConfig['database'] = $name; } @@ -279,14 +279,14 @@ public static function connect($databaseConfig, $label = 'default') throw new InvalidArgumentException("DB::connect: Not passed a valid database config"); } - self::$connection_attempted = true; + DB::$connection_attempted = true; $dbClass = $databaseConfig['type']; // Using Injector->create allows us to use registered configurations // which may or may not map to explicit objects $conn = Injector::inst()->create($dbClass); - self::set_conn($conn, $label); + DB::set_conn($conn, $label); $conn->connect($databaseConfig); return $conn; @@ -323,7 +323,7 @@ public static function getConfig($name = 'default') */ public static function connection_attempted() { - return self::$connection_attempted; + return DB::$connection_attempted; } /** @@ -334,9 +334,9 @@ public static function connection_attempted() */ public static function query($sql, $errorLevel = E_USER_ERROR) { - self::$lastQuery = $sql; + DB::$lastQuery = $sql; - return self::get_conn()->query($sql, $errorLevel); + return DB::get_conn()->query($sql, $errorLevel); } /** @@ -426,9 +426,9 @@ public static function inline_parameters($sql, $parameters) */ public static function prepared_query($sql, $parameters, $errorLevel = E_USER_ERROR) { - self::$lastQuery = $sql; + DB::$lastQuery = $sql; - return self::get_conn()->preparedQuery($sql, $parameters, $errorLevel); + return DB::get_conn()->preparedQuery($sql, $parameters, $errorLevel); } /** @@ -473,8 +473,8 @@ public static function prepared_query($sql, $parameters, $errorLevel = E_USER_ER */ public static function manipulate($manipulation) { - self::$lastQuery = $manipulation; - self::get_conn()->manipulate($manipulation); + DB::$lastQuery = $manipulation; + DB::get_conn()->manipulate($manipulation); } /** @@ -485,7 +485,7 @@ public static function manipulate($manipulation) */ public static function get_generated_id($table) { - return self::get_conn()->getGeneratedID($table); + return DB::get_conn()->getGeneratedID($table); } /** @@ -495,7 +495,7 @@ public static function get_generated_id($table) */ public static function is_active() { - return ($conn = self::get_conn()) && $conn->isActive(); + return ($conn = DB::get_conn()) && $conn->isActive(); } /** @@ -508,7 +508,7 @@ public static function is_active() */ public static function create_database($database) { - return self::get_conn()->selectDatabase($database, true); + return DB::get_conn()->selectDatabase($database, true); } /** @@ -531,7 +531,7 @@ public static function create_table( $options = null, $advancedOptions = null ) { - return self::get_schema()->createTable($table, $fields, $indexes, $options, $advancedOptions); + return DB::get_schema()->createTable($table, $fields, $indexes, $options, $advancedOptions); } /** @@ -542,7 +542,7 @@ public static function create_table( */ public static function create_field($table, $field, $spec) { - return self::get_schema()->createField($table, $field, $spec); + return DB::get_schema()->createField($table, $field, $spec); } /** @@ -568,7 +568,7 @@ public static function require_table( $options = null, $extensions = null ) { - self::get_schema()->requireTable($table, $fieldSchema, $indexSchema, $hasAutoIncPK, $options, $extensions); + DB::get_schema()->requireTable($table, $fieldSchema, $indexSchema, $hasAutoIncPK, $options, $extensions); } /** @@ -580,7 +580,7 @@ public static function require_table( */ public static function require_field($table, $field, $spec) { - self::get_schema()->requireField($table, $field, $spec); + DB::get_schema()->requireField($table, $field, $spec); } /** @@ -592,7 +592,7 @@ public static function require_field($table, $field, $spec) */ public static function require_index($table, $index, $spec) { - self::get_schema()->requireIndex($table, $index, $spec); + DB::get_schema()->requireIndex($table, $index, $spec); } /** @@ -602,7 +602,7 @@ public static function require_index($table, $index, $spec) */ public static function dont_require_table($table) { - self::get_schema()->dontRequireTable($table); + DB::get_schema()->dontRequireTable($table); } /** @@ -613,7 +613,7 @@ public static function dont_require_table($table) */ public static function dont_require_field($table, $fieldName) { - self::get_schema()->dontRequireField($table, $fieldName); + DB::get_schema()->dontRequireField($table, $fieldName); } /** @@ -624,7 +624,7 @@ public static function dont_require_field($table, $fieldName) */ public static function check_and_repair_table($table) { - return self::get_schema()->checkAndRepairTable($table); + return DB::get_schema()->checkAndRepairTable($table); } /** @@ -634,7 +634,7 @@ public static function check_and_repair_table($table) */ public static function affected_rows() { - return self::get_conn()->affectedRows(); + return DB::get_conn()->affectedRows(); } /** @@ -645,7 +645,7 @@ public static function affected_rows() */ public static function table_list() { - return self::get_schema()->tableList(); + return DB::get_schema()->tableList(); } /** @@ -657,7 +657,7 @@ public static function table_list() */ public static function field_list($table) { - return self::get_schema()->fieldList($table); + return DB::get_schema()->fieldList($table); } /** @@ -667,7 +667,7 @@ public static function field_list($table) */ public static function quiet($quiet = true) { - self::get_schema()->quiet($quiet); + DB::get_schema()->quiet($quiet); } /** @@ -678,6 +678,6 @@ public static function quiet($quiet = true) */ public static function alteration_message($message, $type = "") { - self::get_schema()->alterationMessage($message, $type); + DB::get_schema()->alterationMessage($message, $type); } } diff --git a/src/ORM/DataObject.php b/src/ORM/DataObject.php index 42d0166458a..e57fae5aa3d 100644 --- a/src/ORM/DataObject.php +++ b/src/ORM/DataObject.php @@ -339,10 +339,10 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity */ public static function getSchema() { - if (is_null(self::$schema)) { - self::$schema = Injector::inst()->get(DataObjectSchema::class); + if (is_null(DataObject::$schema)) { + DataObject::$schema = Injector::inst()->get(DataObjectSchema::class); } - return self::$schema; + return DataObject::$schema; } /** @@ -354,7 +354,7 @@ public static function getSchema() * left as the default by regular users. * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects. */ - public function __construct($record = [], $creationType = self::CREATE_OBJECT, $queryParams = []) + public function __construct($record = [], $creationType = DataObject::CREATE_OBJECT, $queryParams = []) { parent::__construct(); @@ -368,7 +368,7 @@ public function __construct($record = [], $creationType = self::CREATE_OBJECT, $ if (!is_bool($creationType)) { user_error('Creation type is neither boolean (old isSingleton arg) nor integer (new arg), please review your code', E_USER_WARNING); } - $creationType = $creationType ? self::CREATE_SINGLETON : self::CREATE_OBJECT; + $creationType = $creationType ? DataObject::CREATE_SINGLETON : DataObject::CREATE_OBJECT; } // Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context @@ -379,13 +379,13 @@ public function __construct($record = [], $creationType = self::CREATE_OBJECT, $ switch ($creationType) { // Hydrate a record - case self::CREATE_HYDRATED: - case self::CREATE_MEMORY_HYDRATED: - $this->hydrate($record, $creationType === self::CREATE_HYDRATED); + case DataObject::CREATE_HYDRATED: + case DataObject::CREATE_MEMORY_HYDRATED: + $this->hydrate($record, $creationType === DataObject::CREATE_HYDRATED); break; // Create a new object, using the constructor argument as the initial content - case self::CREATE_OBJECT: + case DataObject::CREATE_OBJECT: if ($record instanceof stdClass) { $record = (array)$record; } @@ -425,7 +425,7 @@ public function __construct($record = [], $creationType = self::CREATE_OBJECT, $ } break; - case self::CREATE_SINGLETON: + case DataObject::CREATE_SINGLETON: // No setting happens for a singleton $this->record['ID'] = 0; $this->record['ClassName'] = static::class; @@ -718,7 +718,7 @@ public function getClassName() public function setClassName($className) { $className = trim($className ?? ''); - if (!$className || !is_subclass_of($className, self::class)) { + if (!$className || !is_subclass_of($className, DataObject::class)) { return $this; } @@ -746,14 +746,14 @@ public function setClassName($className) */ public function newClassInstance($newClassName) { - if (!is_subclass_of($newClassName, self::class)) { + if (!is_subclass_of($newClassName, DataObject::class)) { throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject"); } $originalClass = $this->ClassName; /** @var DataObject $newInstance */ - $newInstance = Injector::inst()->create($newClassName, $this->record, self::CREATE_MEMORY_HYDRATED); + $newInstance = Injector::inst()->create($newClassName, $this->record, DataObject::CREATE_MEMORY_HYDRATED); // Modify ClassName if ($newClassName != $originalClass) { @@ -773,7 +773,7 @@ public function defineMethods() { parent::defineMethods(); - if (static::class === self::class) { + if (static::class === DataObject::class) { return; } @@ -1295,7 +1295,7 @@ protected function onAfterDelete() } /** - * Load the default values in from the self::$defaults array. + * Load the default values in from the DataObject::$defaults array. * Will traverse the defaults of the current class and all its parent classes. * Called by the constructor when creating new records. * @@ -1331,7 +1331,7 @@ public function populateDefaults() } } } - if ($class == self::class) { + if ($class == DataObject::class) { break; } } @@ -1492,7 +1492,7 @@ protected function writeBaseRecord($baseTable, $now) $this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass()); DB::manipulate($manipulation); - $this->changed['ID'] = self::CHANGE_VALUE; + $this->changed['ID'] = DataObject::CHANGE_VALUE; $this->record['ID'] = DB::get_generated_id($baseTable); } @@ -1819,7 +1819,7 @@ public function getComponent($componentName) $joinID = $this->getField($joinField); // Extract class name for polymorphic relations - if ($class === self::class) { + if ($class === DataObject::class) { $class = $this->getField($componentName . 'Class'); if (empty($class)) { return null; @@ -1902,7 +1902,7 @@ public function setComponent($componentName, $item) $this->setField($joinField, $item ? $item->ID : null); // Update Class (Polymorphic has_one) // Extract class name for polymorphic relations - if ($class === self::class) { + if ($class === DataObject::class) { $this->setField($componentName . 'Class', $item ? get_class($item) : null); } } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) { @@ -2081,7 +2081,7 @@ public function inferReciprocalComponent($remoteClass, $remoteRelation) )); } // If relation is polymorphic, do not infer recriprocal relationship - if ($class === self::class) { + if ($class === DataObject::class) { return null; } if (!is_a($this, $class ?? '', true)) { @@ -2444,7 +2444,7 @@ public function scaffoldSearchFields($_params = null) if ($fields->fieldByName($generalSearch) || $fields->dataFieldByName($generalSearch)) { throw new LogicException('General search field name must be unique.'); } - $fields->unshift(HiddenField::create($generalSearch, _t(self::class . '.GENERALSEARCH', 'General Search'))); + $fields->unshift(HiddenField::create($generalSearch, _t(DataObject::class . '.GENERALSEARCH', 'General Search'))); } return $fields; @@ -2742,7 +2742,7 @@ protected function loadLazyFields($class = null) * @param int $changeLevel The strictness of what is defined as change. Defaults to strict * @return array */ - public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) + public function getChangedFields($databaseFieldsOnly = false, $changeLevel = DataObject::CHANGE_STRICT) { $changedFields = []; @@ -2753,15 +2753,15 @@ public function getChangedFields($databaseFieldsOnly = false, $changeLevel = sel continue; } if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) { - $this->changed[$k] = self::CHANGE_VALUE; + $this->changed[$k] = DataObject::CHANGE_VALUE; } } // If change was forced, then derive change data from $this->record - if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) { + if ($this->changeForced && $changeLevel <= DataObject::CHANGE_STRICT) { $changed = array_combine( array_keys($this->record ?? []), - array_fill(0, count($this->record ?? []), self::CHANGE_STRICT) + array_fill(0, count($this->record ?? []), DataObject::CHANGE_STRICT) ); unset($changed['Version']); } else { @@ -2778,7 +2778,7 @@ public function getChangedFields($databaseFieldsOnly = false, $changeLevel = sel } // Filter the list to those of a certain change level - if ($changeLevel > self::CHANGE_STRICT) { + if ($changeLevel > DataObject::CHANGE_STRICT) { if ($fields) { foreach ($fields as $name => $level) { if ($level < $changeLevel) { @@ -2809,7 +2809,7 @@ public function getChangedFields($databaseFieldsOnly = false, $changeLevel = sel * @param int $changeLevel See {@link getChangedFields()} * @return boolean */ - public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) + public function isChanged($fieldName = null, $changeLevel = DataObject::CHANGE_STRICT) { $fields = $fieldName ? [$fieldName] : true; $changed = $this->getChangedFields($fields, $changeLevel); @@ -2897,13 +2897,13 @@ private function setFieldValue(string $fieldName, mixed $val): void // if a field is not existing or has strictly changed if (!array_key_exists($fieldName, $this->original ?? []) || $this->original[$fieldName] !== $val) { // At the very least, the type has changed - $this->changed[$fieldName] = self::CHANGE_STRICT; + $this->changed[$fieldName] = DataObject::CHANGE_STRICT; if ((!array_key_exists($fieldName, $this->original ?? []) && $val) || (array_key_exists($fieldName, $this->original ?? []) && $this->original[$fieldName] != $val) ) { // Value has changed as well, not just the type - $this->changed[$fieldName] = self::CHANGE_VALUE; + $this->changed[$fieldName] = DataObject::CHANGE_VALUE; } // Value has been restored to its original, remove any record of the change } elseif (isset($this->changed[$fieldName])) { @@ -3298,7 +3298,7 @@ public function getReverseAssociation($className) * @param string|array $filter A filter to be inserted into the WHERE clause. * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples. * @param string|array|null $sort Passed to DataList::sort() - * BY clause. If omitted, self::$default_sort will be used. + * BY clause. If omitted, DataObject::$default_sort will be used. * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead. * @param string|array $limit A limit expression to be inserted into the LIMIT clause. * @param string $containerClass The container class to return the results in. @@ -3316,14 +3316,14 @@ public static function get( // Validate arguments if ($callerClass == null) { $callerClass = get_called_class(); - if ($callerClass === self::class) { + if ($callerClass === DataObject::class) { throw new InvalidArgumentException('Call::get() instead of DataObject::get()'); } if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) { throw new InvalidArgumentException('If calling ::get() then you shouldn\'t pass any other' . ' arguments'); } - } elseif ($callerClass === self::class) { + } elseif ($callerClass === DataObject::class) { throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly'); } if ($join) { @@ -3378,7 +3378,7 @@ public static function get_one($callerClass = null, $filter = "", $cache = true, } // Validate class - if ($callerClass === self::class) { + if ($callerClass === DataObject::class) { throw new InvalidArgumentException('DataObject::get_one() cannot query non-subclass DataObject directly'); } @@ -3389,7 +3389,7 @@ public static function get_one($callerClass = null, $filter = "", $cache = true, $cacheKey = md5(serialize($cacheComponents)); $item = null; - if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) { + if (!$cache || !isset(DataObject::$_cache_get_one[$callerClass][$cacheKey])) { $dl = DataObject::get($callerClass); if (!empty($filter)) { $dl = $dl->where($filter); @@ -3400,15 +3400,15 @@ public static function get_one($callerClass = null, $filter = "", $cache = true, $item = $dl->first(); if ($cache) { - self::$_cache_get_one[$callerClass][$cacheKey] = $item; - if (!self::$_cache_get_one[$callerClass][$cacheKey]) { - self::$_cache_get_one[$callerClass][$cacheKey] = false; + DataObject::$_cache_get_one[$callerClass][$cacheKey] = $item; + if (!DataObject::$_cache_get_one[$callerClass][$cacheKey]) { + DataObject::$_cache_get_one[$callerClass][$cacheKey] = false; } } } if ($cache) { - return self::$_cache_get_one[$callerClass][$cacheKey] ?: null; + return DataObject::$_cache_get_one[$callerClass][$cacheKey] ?: null; } return $item; @@ -3424,15 +3424,15 @@ public static function get_one($callerClass = null, $filter = "", $cache = true, */ public function flushCache($persistent = true) { - if (static::class == self::class) { - self::$_cache_get_one = []; + if (static::class == DataObject::class) { + DataObject::$_cache_get_one = []; return $this; } $classes = ClassInfo::ancestry(static::class); foreach ($classes as $class) { - if (isset(self::$_cache_get_one[$class])) { - unset(self::$_cache_get_one[$class]); + if (isset(DataObject::$_cache_get_one[$class])) { + unset(DataObject::$_cache_get_one[$class]); } } @@ -3448,8 +3448,8 @@ public function flushCache($persistent = true) */ public static function flush_and_destroy_cache() { - if (self::$_cache_get_one) { - foreach (self::$_cache_get_one as $class => $items) { + if (DataObject::$_cache_get_one) { + foreach (DataObject::$_cache_get_one as $class => $items) { if (is_array($items)) { foreach ($items as $item) { if ($item) { @@ -3459,7 +3459,7 @@ public static function flush_and_destroy_cache() } } } - self::$_cache_get_one = []; + DataObject::$_cache_get_one = []; } /** @@ -3470,8 +3470,8 @@ public static function reset() DBEnum::flushCache(); ClassInfo::reset_db_cache(); static::getSchema()->reset(); - self::$_cache_get_one = []; - self::$_cache_field_labels = []; + DataObject::$_cache_get_one = []; + DataObject::$_cache_field_labels = []; } /** @@ -3499,7 +3499,7 @@ public static function get_by_id($classOrID, $idOrCache = null, $cache = true) } // Validate class - if ($class === self::class) { + if ($class === DataObject::class) { throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly'); } @@ -3602,7 +3602,7 @@ public function requireTable() $table = $schema->tableName(static::class); $fields = $schema->databaseFields(static::class, false); $indexes = $schema->databaseIndexes(static::class, false); - $extensions = self::database_extensions(static::class); + $extensions = DataObject::database_extensions(static::class); if (empty($table)) { throw new LogicException( @@ -3611,7 +3611,7 @@ public function requireTable() } if ($fields) { - $hasAutoIncPK = get_parent_class($this ?? '') === self::class; + $hasAutoIncPK = get_parent_class($this ?? '') === DataObject::class; DB::require_table( $table, $fields, @@ -3843,7 +3843,7 @@ public function searchableFields() * between data object being required in the search interface. * * Generates labels based on name of the field itself, if no static property - * {@link self::field_labels} exists. + * {@link DataObject::field_labels} exists. * * @uses $field_labels * @uses FormField::name_to_label() @@ -3856,7 +3856,7 @@ public function fieldLabels($includerelations = true) { $cacheKey = static::class . '_' . $includerelations; - if (!isset(self::$_cache_field_labels[$cacheKey])) { + if (!isset(DataObject::$_cache_field_labels[$cacheKey])) { $customLabels = $this->config()->get('field_labels'); $autoLabels = []; @@ -3902,10 +3902,10 @@ public function fieldLabels($includerelations = true) $labels = array_merge((array)$autoLabels, (array)$customLabels); $this->extend('updateFieldLabels', $labels); - self::$_cache_field_labels[$cacheKey] = $labels; + DataObject::$_cache_field_labels[$cacheKey] = $labels; } - return self::$_cache_field_labels[$cacheKey]; + return DataObject::$_cache_field_labels[$cacheKey]; } /** @@ -4024,7 +4024,7 @@ public function isInDB() public static function disable_subclass_access() { Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality'); - self::$subclass_access = false; + DataObject::$subclass_access = false; } /** @@ -4033,7 +4033,7 @@ public static function disable_subclass_access() public static function enable_subclass_access() { Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality'); - self::$subclass_access = true; + DataObject::$subclass_access = true; } //-------------------------------------------------------------------------------------------// diff --git a/src/ORM/DataObjectSchema.php b/src/ORM/DataObjectSchema.php index 6b0acfbce24..9fc2ca6646e 100644 --- a/src/ORM/DataObjectSchema.php +++ b/src/ORM/DataObjectSchema.php @@ -206,9 +206,9 @@ public function fieldSpecs($classOrInstance, $options = 0) if (!is_int($options)) { throw new InvalidArgumentException("Invalid options " . var_export($options, true)); } - $uninherited = ($options & self::UNINHERITED) === self::UNINHERITED; - $dbOnly = ($options & self::DB_ONLY) === self::DB_ONLY; - $includeClass = ($options & self::INCLUDE_CLASS) === self::INCLUDE_CLASS; + $uninherited = ($options & DataObjectSchema::UNINHERITED) === DataObjectSchema::UNINHERITED; + $dbOnly = ($options & DataObjectSchema::DB_ONLY) === DataObjectSchema::DB_ONLY; + $includeClass = ($options & DataObjectSchema::INCLUDE_CLASS) === DataObjectSchema::INCLUDE_CLASS; // Walk class hierarchy $db = []; @@ -513,7 +513,7 @@ protected function cacheDatabaseFields($class) } // Handle has_one which handles multiple reciprocal has_many relations $hasOneClass = $spec['class']; - if (($spec[self::HAS_ONE_MULTI_RELATIONAL] ?? false) === true) { + if (($spec[DataObjectSchema::HAS_ONE_MULTI_RELATIONAL] ?? false) === true) { $compositeFields[$fieldName] = 'PolymorphicRelationAwareForeignKey'; continue; } @@ -577,7 +577,7 @@ protected function cacheDefaultDatabaseIndexes($class) } $this->defaultDatabaseIndexes[$class] = []; - $fieldSpecs = $this->fieldSpecs($class, self::UNINHERITED); + $fieldSpecs = $this->fieldSpecs($class, DataObjectSchema::UNINHERITED); foreach ($fieldSpecs as $field => $spec) { /** @var DBField $fieldObj */ $fieldObj = Injector::inst()->create($spec, $field); @@ -651,7 +651,7 @@ protected function buildSortDatabaseIndexes($class) list ($table, $column) = $this->parseSortColumn(trim($value ?? '')); $table = trim($table ?? '', '"'); $column = trim($column ?? '', '"'); - if ($table && strtolower($table ?? '') !== strtolower(self::tableName($class) ?? '')) { + if ($table && strtolower($table ?? '') !== strtolower(DataObjectSchema::tableName($class) ?? '')) { continue; } if ($this->databaseField($class, $column, false)) { @@ -945,7 +945,7 @@ public function hasOneComponentHandlesMultipleRelations(string $class, string $c } $spec = $hasOnes[$component]; - return ($spec[self::HAS_ONE_MULTI_RELATIONAL] ?? false) === true; + return ($spec[DataObjectSchema::HAS_ONE_MULTI_RELATIONAL] ?? false) === true; } /** @@ -1280,7 +1280,7 @@ private function checkHasOneArraySpec(string $class, string $component, array $s ); } - if (($spec[self::HAS_ONE_MULTI_RELATIONAL] ?? false) === true + if (($spec[DataObjectSchema::HAS_ONE_MULTI_RELATIONAL] ?? false) === true && $spec['class'] !== DataObject::class ) { throw new InvalidArgumentException( diff --git a/src/ORM/DataQuery.php b/src/ORM/DataQuery.php index ef8f6b67b3b..c9230986947 100644 --- a/src/ORM/DataQuery.php +++ b/src/ORM/DataQuery.php @@ -743,7 +743,7 @@ public function with(string $name, DataQuery|SQLSelect $query, array $cteFields $schema = DataObject::getSchema(); // If the query is a DataQuery, make sure all manipulators, joins, etc are applied - if ($query instanceof self) { + if ($query instanceof DataQuery) { $cteDataClass = $query->dataClass(); $query = $query->query(); // DataQuery wants to select ALL columns by default, diff --git a/src/ORM/EagerLoadedList.php b/src/ORM/EagerLoadedList.php index 8bec6c948bc..8a53c88905d 100644 --- a/src/ORM/EagerLoadedList.php +++ b/src/ORM/EagerLoadedList.php @@ -59,7 +59,7 @@ class EagerLoadedList extends ViewableData implements Relation, SS_List, Filtera /** * Nested eager-loaded data which applies to relations on records contained in this list - * @var array + * @var array */ private array $eagerLoadedData = []; @@ -148,7 +148,7 @@ private function isValidForeignID(int|array|null $foreignID): bool * * @return $this */ - public function addEagerLoadedData(string $relation, int $id, self|DataObject $data): static + public function addEagerLoadedData(string $relation, int $id, EagerLoadedList|DataObject $data): static { $this->eagerLoadedData[$id][$relation] = $data; return $this; @@ -856,7 +856,7 @@ public function relation($relationName): ?Relation continue; } $data = $this->eagerLoadedData[$id][$relationName]; - if (!($data instanceof self)) { + if (!($data instanceof EagerLoadedList)) { // There's no clean way to get the rows back out of DataObject records, // and if it's not a DataObject then we don't know how to handle it, // so fall back to a new DB query diff --git a/src/ORM/FieldType/DBDate.php b/src/ORM/FieldType/DBDate.php index b19633d8724..a035d018884 100644 --- a/src/ORM/FieldType/DBDate.php +++ b/src/ORM/FieldType/DBDate.php @@ -45,7 +45,7 @@ public function setValue($value, $record = null, $markChanged = true) $value = $this->parseDate($value); if ($value === false) { throw new InvalidArgumentException( - "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." + "Invalid date: '$value'. Use " . DBDate::ISO_DATE . " to prevent this error." ); } $this->value = $value; @@ -254,7 +254,7 @@ protected function getInternalFormatter() */ public function getISOFormat() { - return self::ISO_DATE; + return DBDate::ISO_DATE; } /** @@ -543,7 +543,7 @@ public function InFuture() */ public function IsToday() { - return $this->Format(self::ISO_DATE) === DBDatetime::now()->Format(self::ISO_DATE); + return $this->Format(DBDate::ISO_DATE) === DBDatetime::now()->Format(DBDate::ISO_DATE); } /** @@ -559,7 +559,7 @@ public function IsToday() * @param string $adjustment PHP strtotime style * @return $this */ - public function modify(string $adjustment): self + public function modify(string $adjustment): DBDate { $modifiedTime = strtotime($adjustment ?? '', $this->getTimestamp()); return $this->setValue($modifiedTime); @@ -572,7 +572,7 @@ public function modify(string $adjustment): self */ public function URLDate() { - return rawurlencode($this->Format(self::ISO_DATE, self::ISO_LOCALE) ?? ''); + return rawurlencode($this->Format(DBDate::ISO_DATE, DBDate::ISO_LOCALE) ?? ''); } public function scaffoldFormField($title = null, $params = null) @@ -600,7 +600,7 @@ protected function fixInputDate($value) // Validate date if (!checkdate($month ?? 0, $day ?? 0, $year ?? 0)) { throw new InvalidArgumentException( - "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." + "Invalid date: '$value'. Use " . DBDate::ISO_DATE . " to prevent this error." ); } @@ -623,7 +623,7 @@ protected function explodeDateString($value) $matches )) { throw new InvalidArgumentException( - "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." + "Invalid date: '$value'. Use " . DBDate::ISO_DATE . " to prevent this error." ); } @@ -638,7 +638,7 @@ protected function explodeDateString($value) } if ($parts[0] < 1000 && (int)$parts[0] !== 0) { throw new InvalidArgumentException( - "Invalid date: '$value'. Use " . self::ISO_DATE . " to prevent this error." + "Invalid date: '$value'. Use " . DBDate::ISO_DATE . " to prevent this error." ); } $parts[] = $matches['time']; diff --git a/src/ORM/FieldType/DBDatetime.php b/src/ORM/FieldType/DBDatetime.php index ca3c49e7a7b..877c707f260 100644 --- a/src/ORM/FieldType/DBDatetime.php +++ b/src/ORM/FieldType/DBDatetime.php @@ -58,7 +58,7 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider * @param bool $immutable * @return $this */ - public function setImmutable(bool $immutable): self + public function setImmutable(bool $immutable): DBDatetime { $this->immutable = $immutable; @@ -172,7 +172,7 @@ public function requireField() */ public function URLDatetime() { - return rawurlencode($this->Format(self::ISO_DATETIME, self::ISO_LOCALE) ?? ''); + return rawurlencode($this->Format(DBDatetime::ISO_DATETIME, DBDatetime::ISO_LOCALE) ?? ''); } public function scaffoldFormField($title = null, $params = null) @@ -208,7 +208,7 @@ public function scaffoldFormField($title = null, $params = null) */ public static function now() { - $time = self::$mock_now ? self::$mock_now->Value : time(); + $time = DBDatetime::$mock_now ? DBDatetime::$mock_now->Value : time(); /** @var DBDatetime $now */ $now = DBField::create_field('Datetime', $time); @@ -233,7 +233,7 @@ public static function set_mock_now($datetime) throw new InvalidArgumentException('DBDatetime::set_mock_now(): Wrong format: ' . $value); } } - self::$mock_now = $datetime; + DBDatetime::$mock_now = $datetime; } /** @@ -242,7 +242,7 @@ public static function set_mock_now($datetime) */ public static function clear_mock_now() { - self::$mock_now = null; + DBDatetime::$mock_now = null; } /** @@ -255,14 +255,14 @@ public static function clear_mock_now() */ public static function withFixedNow($time, $callback) { - $original = self::$mock_now; + $original = DBDatetime::$mock_now; try { - self::set_mock_now($time); + DBDatetime::set_mock_now($time); return $callback(); } finally { - self::$mock_now = $original; + DBDatetime::$mock_now = $original; } } @@ -324,6 +324,6 @@ protected function getInternalFormatter() */ public function getISOFormat() { - return self::ISO_DATETIME; + return DBDatetime::ISO_DATETIME; } } diff --git a/src/ORM/FieldType/DBEnum.php b/src/ORM/FieldType/DBEnum.php index 31df29c462b..b85dec01361 100644 --- a/src/ORM/FieldType/DBEnum.php +++ b/src/ORM/FieldType/DBEnum.php @@ -45,7 +45,7 @@ class DBEnum extends DBString */ public static function flushCache() { - self::$enum_cache = []; + DBEnum::$enum_cache = []; } /** @@ -209,13 +209,13 @@ public function getEnumObsolete() } // Ensure the table level cache exists - if (empty(self::$enum_cache[$table])) { - self::$enum_cache[$table] = []; + if (empty(DBEnum::$enum_cache[$table])) { + DBEnum::$enum_cache[$table] = []; } // Check existing cache - if (!empty(self::$enum_cache[$table][$name])) { - return self::$enum_cache[$table][$name]; + if (!empty(DBEnum::$enum_cache[$table][$name])) { + return DBEnum::$enum_cache[$table][$name]; } // Get all enum values @@ -226,7 +226,7 @@ public function getEnumObsolete() } // Cache and return - self::$enum_cache[$table][$name] = $enumValues; + DBEnum::$enum_cache[$table][$name] = $enumValues; return $enumValues; } diff --git a/src/ORM/FieldType/DBField.php b/src/ORM/FieldType/DBField.php index 079df6b8faf..94b5ee31f15 100644 --- a/src/ORM/FieldType/DBField.php +++ b/src/ORM/FieldType/DBField.php @@ -540,7 +540,7 @@ public function saveInto($dataObject) "DBField::saveInto() Called on a nameless '" . static::class . "' object" ); } - if ($this->value instanceof self) { + if ($this->value instanceof DBField) { $this->value->saveInto($dataObject); } else { $dataObject->__set($fieldName, $this->value); diff --git a/src/ORM/FieldType/DBForeignKey.php b/src/ORM/FieldType/DBForeignKey.php index ab23db7489b..8b2aaa70b32 100644 --- a/src/ORM/FieldType/DBForeignKey.php +++ b/src/ORM/FieldType/DBForeignKey.php @@ -77,7 +77,7 @@ public function scaffoldFormField($title = null, $params = null) } $labelField = $hasOneSingleton->hasField('Title') ? 'Title' : 'Name'; $list = DataList::create($hasOneClass); - $threshold = self::config()->get('dropdown_field_threshold'); + $threshold = static::config()->get('dropdown_field_threshold'); $overThreshold = $list->count() > $threshold; $field = SearchableDropdownField::create($this->name, $title, $list, $labelField) ->setIsLazyLoaded($overThreshold) diff --git a/src/ORM/FieldType/DBString.php b/src/ORM/FieldType/DBString.php index 5427aafd930..875936d5650 100644 --- a/src/ORM/FieldType/DBString.php +++ b/src/ORM/FieldType/DBString.php @@ -237,6 +237,6 @@ private function addEllipsis(string $string, $add): string */ public function defaultEllipsis(): string { - return _t(self::class . '.ELLIPSIS', '…'); + return _t(DBString::class . '.ELLIPSIS', '…'); } } diff --git a/src/ORM/FieldType/DBTime.php b/src/ORM/FieldType/DBTime.php index 54c680aef29..6b1813eea5a 100644 --- a/src/ORM/FieldType/DBTime.php +++ b/src/ORM/FieldType/DBTime.php @@ -174,7 +174,7 @@ public function FormatFromSettings($member = null) */ public function getISOFormat() { - return self::ISO_TIME; + return DBTime::ISO_TIME; } /** diff --git a/src/ORM/Filters/SearchFilter.php b/src/ORM/Filters/SearchFilter.php index daf06f987fd..5da4baba3cd 100644 --- a/src/ORM/Filters/SearchFilter.php +++ b/src/ORM/Filters/SearchFilter.php @@ -474,7 +474,7 @@ protected function getCaseSensitive() } elseif (in_array('nocase', $modifiers ?? [])) { return false; } else { - $sensitive = self::config()->get('default_case_sensitive'); + $sensitive = static::config()->get('default_case_sensitive'); if ($sensitive !== null) { return $sensitive; } @@ -488,13 +488,13 @@ protected function getCaseSensitive() */ protected function getCaseSensitiveByCollation(): ?bool { - if (!self::$caseSensitiveByCollation) { + if (!SearchFilter::$caseSensitiveByCollation) { if (!DB::is_active()) { return null; } - self::$caseSensitiveByCollation = DB::query("SELECT 'CASE' = 'case'")->record() === 0; + SearchFilter::$caseSensitiveByCollation = DB::query("SELECT 'CASE' = 'case'")->record() === 0; } - return self::$caseSensitiveByCollation; + return SearchFilter::$caseSensitiveByCollation; } } diff --git a/src/ORM/Hierarchy/Hierarchy.php b/src/ORM/Hierarchy/Hierarchy.php index 41d5411fe86..40adbb8bf2e 100644 --- a/src/ORM/Hierarchy/Hierarchy.php +++ b/src/ORM/Hierarchy/Hierarchy.php @@ -298,9 +298,9 @@ public function numChildren($cache = true) // cached call if ($cache) { - if (isset(self::$cache_numChildren[$baseClass][$cacheType][$id])) { - return self::$cache_numChildren[$baseClass][$cacheType][$id]; - } elseif (isset(self::$cache_numChildren[$baseClass][$cacheType]['_complete'])) { + if (isset(Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id])) { + return Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id]; + } elseif (isset(Hierarchy::$cache_numChildren[$baseClass][$cacheType]['_complete'])) { // If the cache is complete and we didn't find our ID in the cache, it means this object is childless. return 0; } @@ -311,7 +311,7 @@ public function numChildren($cache = true) // Save if caching if ($cache) { - self::$cache_numChildren[$baseClass][$cacheType][$id] = $numChildren; + Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id] = $numChildren; } return $numChildren; @@ -333,7 +333,7 @@ public function prepopulateTreeDataCache($recordList = null, array $options = [] if (empty($options['numChildrenMethod']) || $options['numChildrenMethod'] === 'numChildren') { $idList = is_array($recordList) ? $recordList : ($recordList instanceof DataList ? $recordList->column('ID') : null); - self::prepopulate_numchildren_cache($this->getHierarchyBaseClass(), $idList); + Hierarchy::prepopulate_numchildren_cache($this->getHierarchyBaseClass(), $idList); } $this->owner->extend('onPrepopulateTreeDataCache', $recordList, $options); @@ -384,11 +384,11 @@ public static function prepopulate_numchildren_cache($baseClass, $idList = null) $query->setGroupBy([Convert::symbol2sql("ParentID")]); $numChildren = $query->execute()->map(); - self::$cache_numChildren[$baseClass]['numChildren'] = $numChildren; + Hierarchy::$cache_numChildren[$baseClass]['numChildren'] = $numChildren; if (!$idList) { // If all objects are being cached, mark this cache as complete // to avoid counting children of childless object. - self::$cache_numChildren[$baseClass]['numChildren']['_complete'] = true; + Hierarchy::$cache_numChildren[$baseClass]['numChildren']['_complete'] = true; } } @@ -416,7 +416,7 @@ private function getHierarchyBaseClass(): string { $ancestry = ClassInfo::ancestry($this->owner); $ancestorClass = array_shift($ancestry); - while ($ancestorClass && !ViewableData::has_extension($ancestorClass, self::class)) { + while ($ancestorClass && !ViewableData::has_extension($ancestorClass, Hierarchy::class)) { $ancestorClass = array_shift($ancestry); } @@ -575,6 +575,6 @@ public function getBreadcrumbs($separator = ' » ') public function flushCache() { $this->owner->_cache_children = null; - self::$cache_numChildren = []; + Hierarchy::$cache_numChildren = []; } } diff --git a/src/ORM/Hierarchy/MarkedSet.php b/src/ORM/Hierarchy/MarkedSet.php index 18dc593fabd..464480c16fd 100644 --- a/src/ORM/Hierarchy/MarkedSet.php +++ b/src/ORM/Hierarchy/MarkedSet.php @@ -275,7 +275,7 @@ public function renderChildren( if (!$template) { $template = [ 'type' => 'Includes', - self::class . '_HTML' + MarkedSet::class . '_HTML' ]; } $tree = $this->getSubtree($this->rootNode, 0); diff --git a/src/ORM/ListDecorator.php b/src/ORM/ListDecorator.php index c7a465a03ad..b063acb7481 100644 --- a/src/ORM/ListDecorator.php +++ b/src/ORM/ListDecorator.php @@ -54,7 +54,7 @@ public function getList(): SS_List&Sortable&Filterable&Limitable * @param TListA $list * @return static */ - public function setList(SS_List&Sortable&Filterable&Limitable $list): self + public function setList(SS_List&Sortable&Filterable&Limitable $list): ListDecorator { $this->list = $list; $this->failover = $this->list; diff --git a/src/ORM/Queries/SQLConditionalExpression.php b/src/ORM/Queries/SQLConditionalExpression.php index 52a7c0ef24a..20c16c61a5f 100644 --- a/src/ORM/Queries/SQLConditionalExpression.php +++ b/src/ORM/Queries/SQLConditionalExpression.php @@ -241,7 +241,7 @@ public function queriedTables() foreach ($this->from as $key => $tableClause) { if (is_array($tableClause)) { $table = '"' . $tableClause['table'] . '"'; - } elseif (is_string($tableClause) && preg_match(self::getJoinRegex(), $tableClause ?? '', $matches)) { + } elseif (is_string($tableClause) && preg_match(SQLConditionalExpression::getJoinRegex(), $tableClause ?? '', $matches)) { $table = $matches[1]; } else { $table = $tableClause; @@ -341,7 +341,7 @@ protected function getOrderedJoins($from) // Remove the regular FROM tables out so we only deal with the JOINs $regularTables = []; foreach ($from as $alias => $tableClause) { - if (is_string($tableClause) && !preg_match(self::getJoinRegex(), $tableClause)) { + if (is_string($tableClause) && !preg_match(SQLConditionalExpression::getJoinRegex(), $tableClause)) { $regularTables[$alias] = $tableClause; unset($from[$alias]); } diff --git a/src/ORM/Queries/SQLSelect.php b/src/ORM/Queries/SQLSelect.php index 9ea1591846a..ed0fc4cd197 100644 --- a/src/ORM/Queries/SQLSelect.php +++ b/src/ORM/Queries/SQLSelect.php @@ -560,7 +560,7 @@ public function getHavingParameterised(&$parameters) */ public function addUnion(SQLSelect $query, ?string $type = null): static { - if ($type && $type !== self::UNION_ALL && $type !== self::UNION_DISTINCT) { + if ($type && $type !== SQLSelect::UNION_ALL && $type !== SQLSelect::UNION_DISTINCT) { throw new LogicException('Union $type must be one of the constants UNION_ALL or UNION_DISTINCT.'); } diff --git a/src/ORM/Search/FulltextSearchable.php b/src/ORM/Search/FulltextSearchable.php index 1eeff1fd64b..a4731e593a2 100644 --- a/src/ORM/Search/FulltextSearchable.php +++ b/src/ORM/Search/FulltextSearchable.php @@ -77,7 +77,7 @@ public static function enable($searchableClasses = [SiteTree::class, File::class ); } } - self::$searchable_classes = $searchableClasses; + FulltextSearchable::$searchable_classes = $searchableClasses; if (class_exists("SilverStripe\\CMS\\Controllers\\ContentController")) { ContentController::add_extension("SilverStripe\\CMS\\Search\\ContentControllerSearchExtension"); } @@ -120,6 +120,6 @@ public static function get_extra_config($class, $extensionClass, $args) */ public static function get_searchable_classes() { - return self::$searchable_classes; + return FulltextSearchable::$searchable_classes; } } diff --git a/src/ORM/Search/SearchContext.php b/src/ORM/Search/SearchContext.php index 7cd78233177..0c6834353e7 100644 --- a/src/ORM/Search/SearchContext.php +++ b/src/ORM/Search/SearchContext.php @@ -81,7 +81,7 @@ class SearchContext /** * A key value pair of values that should be searched for. - * The keys should match the field names specified in {@link self::$fields}. + * The keys should match the field names specified in {@link SearchContext::$fields}. * Usually these values come from a submitted searchform * in the form of a $_REQUEST object. * CAUTION: All values should be treated as insecure client input. diff --git a/src/ORM/ValidationResult.php b/src/ORM/ValidationResult.php index 6d45996d5b7..8ba3ba545ba 100644 --- a/src/ORM/ValidationResult.php +++ b/src/ORM/ValidationResult.php @@ -73,7 +73,7 @@ class ValidationResult * Bool values will be treated as plain text flag. * @return $this */ - public function addError($message, $messageType = self::TYPE_ERROR, $code = null, $cast = self::CAST_TEXT) + public function addError($message, $messageType = ValidationResult::TYPE_ERROR, $code = null, $cast = ValidationResult::CAST_TEXT) { return $this->addFieldError(null, $message, $messageType, $code, $cast); } @@ -94,9 +94,9 @@ public function addError($message, $messageType = self::TYPE_ERROR, $code = null public function addFieldError( $fieldName, $message, - $messageType = self::TYPE_ERROR, + $messageType = ValidationResult::TYPE_ERROR, $code = null, - $cast = self::CAST_TEXT + $cast = ValidationResult::CAST_TEXT ) { $this->isValid = false; return $this->addFieldMessage($fieldName, $message, $messageType, $code, $cast); @@ -114,7 +114,7 @@ public function addFieldError( * Bool values will be treated as plain text flag. * @return $this */ - public function addMessage($message, $messageType = self::TYPE_ERROR, $code = null, $cast = self::CAST_TEXT) + public function addMessage($message, $messageType = ValidationResult::TYPE_ERROR, $code = null, $cast = ValidationResult::CAST_TEXT) { return $this->addFieldMessage(null, $message, $messageType, $code, $cast); } @@ -135,15 +135,15 @@ public function addMessage($message, $messageType = self::TYPE_ERROR, $code = nu public function addFieldMessage( $fieldName, $message, - $messageType = self::TYPE_ERROR, + $messageType = ValidationResult::TYPE_ERROR, $code = null, - $cast = self::CAST_TEXT + $cast = ValidationResult::CAST_TEXT ) { if ($code && is_numeric($code)) { throw new InvalidArgumentException("Don't use a numeric code '$code'. Use a string."); } if (is_bool($cast)) { - $cast = $cast ? self::CAST_TEXT : self::CAST_HTML; + $cast = $cast ? ValidationResult::CAST_TEXT : ValidationResult::CAST_HTML; } $metadata = [ 'message' => $message, diff --git a/src/Security/BasicAuth.php b/src/Security/BasicAuth.php index 9c47c1f1d6c..d99d7802d90 100644 --- a/src/Security/BasicAuth.php +++ b/src/Security/BasicAuth.php @@ -43,7 +43,7 @@ class BasicAuth /** * @config - * @var Boolean Flag set by {@link self::protect_entire_site()} + * @var Boolean Flag set by {@link BasicAuth::protect_entire_site()} */ private static $entire_site_protected = false; @@ -187,7 +187,7 @@ public static function requireLogin( * of the permission codes a user has. * @param string $message */ - public static function protect_entire_site($protect = true, $code = self::AUTH_PERMISSION, $message = null) + public static function protect_entire_site($protect = true, $code = BasicAuth::AUTH_PERMISSION, $message = null) { static::config() ->set('entire_site_protected', $protect) @@ -214,11 +214,11 @@ public static function protect_site_if_necessary(HTTPRequest $request = null) // Check if site is protected if ($config->get('entire_site_protected')) { $permissionCode = $config->get('entire_site_protected_code'); - } elseif (Environment::getEnv(self::USE_BASIC_AUTH)) { + } elseif (Environment::getEnv(BasicAuth::USE_BASIC_AUTH)) { // Convert legacy 1 / true to ADMIN permissions - $permissionCode = Environment::getEnv(self::USE_BASIC_AUTH); + $permissionCode = Environment::getEnv(BasicAuth::USE_BASIC_AUTH); if (!is_string($permissionCode) || is_numeric($permissionCode)) { - $permissionCode = self::AUTH_PERMISSION; + $permissionCode = BasicAuth::AUTH_PERMISSION; } } else { // Not enabled diff --git a/src/Security/Confirmation/Storage.php b/src/Security/Confirmation/Storage.php index ef4e01720fa..01f82239805 100644 --- a/src/Security/Confirmation/Storage.php +++ b/src/Security/Confirmation/Storage.php @@ -368,7 +368,7 @@ public function setSuccessUrl($url) } /** - * Returns the URL registered by {@see self::setSuccessUrl} as a success redirect target + * Returns the URL registered by {@see Storage::setSuccessUrl} as a success redirect target * * @return string */ @@ -391,7 +391,7 @@ public function setFailureUrl($url) } /** - * Returns the URL registered by {@see self::setFailureUrl} as a success redirect target + * Returns the URL registered by {@see Storage::setFailureUrl} as a success redirect target * * @return string */ diff --git a/src/Security/InheritedPermissions.php b/src/Security/InheritedPermissions.php index bcaa1f6b654..65b66044819 100644 --- a/src/Security/InheritedPermissions.php +++ b/src/Security/InheritedPermissions.php @@ -147,7 +147,7 @@ public function flushMemberCache($memberIDs = null) } if ($memberIDs && is_array($memberIDs)) { - foreach ([self::VIEW, self::EDIT, self::DELETE] as $type) { + foreach ([InheritedPermissions::VIEW, InheritedPermissions::EDIT, InheritedPermissions::DELETE] as $type) { foreach ($memberIDs as $memberID) { $key = $this->generateCacheKey($type, $memberID); $this->cacheService->delete($key); @@ -215,13 +215,13 @@ public function getBaseClass() public function prePopulatePermissionCache($permission = 'edit', $ids = []) { switch ($permission) { - case self::EDIT: + case InheritedPermissions::EDIT: $this->canEditMultiple($ids, Security::getCurrentUser(), false); break; - case self::VIEW: + case InheritedPermissions::VIEW: $this->canViewMultiple($ids, Security::getCurrentUser(), false); break; - case self::DELETE: + case InheritedPermissions::DELETE: $this->canDeleteMultiple($ids, Security::getCurrentUser(), false); break; default: @@ -265,7 +265,7 @@ protected function batchPermissionCheck( // Validate member permission // Only VIEW allows anonymous (Anyone) permissions $memberID = $member ? (int)$member->ID : 0; - if (!$memberID && $type !== self::VIEW) { + if (!$memberID && $type !== InheritedPermissions::VIEW) { return $result; } @@ -374,10 +374,10 @@ protected function batchPermissionCheckForStage( . " OR (\"$typeField\" = ? AND \"$memberJoinTable\".\"{$baseTable}ID\" IS NOT NULL)" . ")" => [ - self::ANYONE, - self::LOGGED_IN_USERS, - self::ONLY_THESE_USERS, - self::ONLY_THESE_MEMBERS, + InheritedPermissions::ANYONE, + InheritedPermissions::LOGGED_IN_USERS, + InheritedPermissions::ONLY_THESE_USERS, + InheritedPermissions::ONLY_THESE_MEMBERS, ] ]) ->leftJoin( @@ -393,7 +393,7 @@ protected function batchPermissionCheckForStage( } else { // Only view pages with ViewType = Anyone if not logged in $uninheritedPermissions = $stageRecords - ->filter($typeField, self::ANYONE) + ->filter($typeField, InheritedPermissions::ANYONE) ->column('ID'); } @@ -406,7 +406,7 @@ protected function batchPermissionCheckForStage( // We group these and run a batch permission check on all parents. This gives us the result // of whether the user has permission to edit this object. $groupedByParent = []; - $potentiallyInherited = $stageRecords->filter($typeField, self::INHERIT) + $potentiallyInherited = $stageRecords->filter($typeField, InheritedPermissions::INHERIT) ->orderBy("\"{$baseTable}\".\"ID\"") ->dataQuery() ->query() @@ -456,7 +456,7 @@ protected function batchPermissionCheckForStage( public function canEditMultiple($ids, Member $member = null, $useCached = true) { return $this->batchPermissionCheck( - self::EDIT, + InheritedPermissions::EDIT, $ids, $member, $this->getGlobalEditPermissions(), @@ -472,7 +472,7 @@ public function canEditMultiple($ids, Member $member = null, $useCached = true) */ public function canViewMultiple($ids, Member $member = null, $useCached = true) { - return $this->batchPermissionCheck(self::VIEW, $ids, $member, [], $useCached); + return $this->batchPermissionCheck(InheritedPermissions::VIEW, $ids, $member, [], $useCached); } /** @@ -559,7 +559,7 @@ public function canDelete($id, Member $member = null) { // No ID: Check default permission if (!$id) { - return $this->checkDefaultPermissions(self::DELETE, $member); + return $this->checkDefaultPermissions(InheritedPermissions::DELETE, $member); } // Regular canEdit logic is handled by canEditMultiple @@ -581,7 +581,7 @@ public function canEdit($id, Member $member = null) { // No ID: Check default permission if (!$id) { - return $this->checkDefaultPermissions(self::EDIT, $member); + return $this->checkDefaultPermissions(InheritedPermissions::EDIT, $member); } // Regular canEdit logic is handled by canEditMultiple @@ -603,7 +603,7 @@ public function canView($id, Member $member = null) { // No ID: Check default permission if (!$id) { - return $this->checkDefaultPermissions(self::VIEW, $member); + return $this->checkDefaultPermissions(InheritedPermissions::VIEW, $member); } // Regular canView logic is handled by canViewMultiple @@ -626,11 +626,11 @@ public function canView($id, Member $member = null) protected function getPermissionField($type) { switch ($type) { - case self::DELETE: + case InheritedPermissions::DELETE: // Delete uses edit type - Drop through - case self::EDIT: + case InheritedPermissions::EDIT: return 'CanEditType'; - case self::VIEW: + case InheritedPermissions::VIEW: return 'CanViewType'; default: throw new InvalidArgumentException("Invalid argument type $type"); @@ -661,11 +661,11 @@ protected function getJoinTable($type) protected function getGroupJoinTable($type) { switch ($type) { - case self::DELETE: + case InheritedPermissions::DELETE: // Delete uses edit type - Drop through - case self::EDIT: + case InheritedPermissions::EDIT: return $this->getEditorGroupsTable(); - case self::VIEW: + case InheritedPermissions::VIEW: return $this->getViewerGroupsTable(); default: throw new InvalidArgumentException("Invalid argument type $type"); @@ -682,11 +682,11 @@ protected function getGroupJoinTable($type) protected function getMemberJoinTable($type) { switch ($type) { - case self::DELETE: + case InheritedPermissions::DELETE: // Delete uses edit type - Drop through - case self::EDIT: + case InheritedPermissions::EDIT: return $this->getEditorMembersTable(); - case self::VIEW: + case InheritedPermissions::VIEW: return $this->getViewerMembersTable(); default: throw new InvalidArgumentException("Invalid argument type $type"); @@ -707,11 +707,11 @@ protected function checkDefaultPermissions($type, Member $member = null) return false; } switch ($type) { - case self::VIEW: + case InheritedPermissions::VIEW: return $defaultPermissions->canView($member); - case self::EDIT: + case InheritedPermissions::EDIT: return $defaultPermissions->canEdit($member); - case self::DELETE: + case InheritedPermissions::DELETE: return $defaultPermissions->canDelete($member); default: return false; diff --git a/src/Security/LogoutForm.php b/src/Security/LogoutForm.php index e8851c51e07..03ad3a05965 100644 --- a/src/Security/LogoutForm.php +++ b/src/Security/LogoutForm.php @@ -23,7 +23,7 @@ class LogoutForm extends Form */ public function __construct( RequestHandler $controller = null, - $name = self::DEFAULT_NAME, + $name = LogoutForm::DEFAULT_NAME, FieldList $fields = null, FieldList $actions = null, Validator $validator = null diff --git a/src/Security/Member.php b/src/Security/Member.php index 446ca658888..2003e8f05cd 100644 --- a/src/Security/Member.php +++ b/src/Security/Member.php @@ -478,7 +478,7 @@ public function afterMemberLoggedIn() public function regenerateTempID() { $generator = new RandomGenerator(); - $lifetime = self::config()->get('temp_id_lifetime'); + $lifetime = static::config()->get('temp_id_lifetime'); $this->TempIDHash = $generator->randomToken('sha1'); $this->TempIDExpired = $lifetime ? date('Y-m-d H:i:s', strtotime(DBDatetime::now()->getValue()) + $lifetime) @@ -565,7 +565,7 @@ public function generateAutologinTokenAndStoreHash() public function validateAutoLoginToken($autologinToken) { $hash = $this->encryptWithUserSettings($autologinToken); - $member = self::member_from_autologinhash($hash, false); + $member = Member::member_from_autologinhash($hash, false); return (bool)$member; } @@ -1615,7 +1615,7 @@ public function changePassword($password, $write = true) protected function encryptPassword() { // reset salt so that it gets regenerated - this will invalidate any persistent login cookies - // or other information encrypted with this Member's settings (see self::encryptWithUserSettings) + // or other information encrypted with this Member's settings (see Member::encryptWithUserSettings) $this->Salt = ''; // Password was changed: encrypt the password according the settings @@ -1650,13 +1650,13 @@ protected function encryptPassword() */ public function registerFailedLogin() { - $lockOutAfterCount = self::config()->get('lock_out_after_incorrect_logins'); + $lockOutAfterCount = static::config()->get('lock_out_after_incorrect_logins'); if ($lockOutAfterCount) { // Keep a tally of the number of failed log-ins so that we can lock people out ++$this->FailedLoginCount; if ($this->FailedLoginCount >= $lockOutAfterCount) { - $lockoutMins = self::config()->get('lock_out_delay_mins'); + $lockoutMins = static::config()->get('lock_out_delay_mins'); $this->LockedOutUntil = date('Y-m-d H:i:s', DBDatetime::now()->getTimestamp() + $lockoutMins * 60); $this->FailedLoginCount = 0; } @@ -1670,7 +1670,7 @@ public function registerFailedLogin() */ public function registerSuccessfulLogin() { - if (self::config()->get('lock_out_after_incorrect_logins')) { + if (static::config()->get('lock_out_after_incorrect_logins')) { // Forgive all past login failures $this->FailedLoginCount = 0; $this->LockedOutUntil = null; @@ -1714,7 +1714,7 @@ public function getHtmlEditorConfigForCMS() public function generateRandomPassword(int $length = 0): string { $password = ''; - $validator = self::password_validator(); + $validator = Member::password_validator(); if ($length && $validator && $length < $validator->getMinLength()) { throw new InvalidArgumentException('length argument is less than password validator minLength'); } diff --git a/src/Security/MemberAuthenticator/MemberLoginForm.php b/src/Security/MemberAuthenticator/MemberLoginForm.php index 94dd5027d1c..eba6afc74dd 100644 --- a/src/Security/MemberAuthenticator/MemberLoginForm.php +++ b/src/Security/MemberAuthenticator/MemberLoginForm.php @@ -111,7 +111,7 @@ public function __construct( if (isset($logoutAction)) { $this->setFormAction($logoutAction); } - $this->setValidator(RequiredFields::create(self::config()->get('required_fields'))); + $this->setValidator(RequiredFields::create(static::config()->get('required_fields'))); } /** @@ -225,6 +225,6 @@ public function restoreFormState() */ public function getAuthenticatorName() { - return _t(self::class . '.AUTHENTICATORNAME', "E-mail & Password"); + return _t(MemberLoginForm::class . '.AUTHENTICATORNAME', "E-mail & Password"); } } diff --git a/src/Security/PasswordEncryptor.php b/src/Security/PasswordEncryptor.php index 56e42af7f78..cbf6484877b 100644 --- a/src/Security/PasswordEncryptor.php +++ b/src/Security/PasswordEncryptor.php @@ -28,7 +28,7 @@ abstract class PasswordEncryptor */ public static function get_encryptors() { - return Config::inst()->get(self::class, 'encryptors'); + return Config::inst()->get(PasswordEncryptor::class, 'encryptors'); } /** @@ -38,7 +38,7 @@ public static function get_encryptors() */ public static function create_for_algorithm($algorithm) { - $encryptors = self::get_encryptors(); + $encryptors = PasswordEncryptor::get_encryptors(); if (!isset($encryptors[$algorithm])) { throw new PasswordEncryptor_NotFoundException( sprintf('No implementation found for "%s"', $algorithm) diff --git a/src/Security/PasswordEncryptor_Blowfish.php b/src/Security/PasswordEncryptor_Blowfish.php index 877fdd1247b..0b6277d8f3f 100644 --- a/src/Security/PasswordEncryptor_Blowfish.php +++ b/src/Security/PasswordEncryptor_Blowfish.php @@ -30,7 +30,7 @@ class PasswordEncryptor_Blowfish extends PasswordEncryptor */ public static function set_cost($cost) { - self::$cost = max(min(31, $cost), 4); + PasswordEncryptor_Blowfish::$cost = max(min(31, $cost), 4); } /** @@ -40,7 +40,7 @@ public static function set_cost($cost) */ public static function get_cost() { - return self::$cost; + return PasswordEncryptor_Blowfish::$cost; } public function encrypt($password, $salt = null, $member = null) @@ -153,7 +153,7 @@ public function checkAEncryptionLevel() } /** - * self::$cost param is forced to be two digits with leading zeroes for ints 4-9 + * PasswordEncryptor_Blowfish::$cost param is forced to be two digits with leading zeroes for ints 4-9 * * @param string $password * @param Member $member @@ -162,7 +162,7 @@ public function checkAEncryptionLevel() public function salt($password, $member = null) { $generator = new RandomGenerator(); - return sprintf('%02d', self::$cost) . '$' . substr($generator->randomToken('sha1') ?? '', 0, 22); + return sprintf('%02d', PasswordEncryptor_Blowfish::$cost) . '$' . substr($generator->randomToken('sha1') ?? '', 0, 22); } public function check($hash, $password, $salt = null, $member = null) diff --git a/src/Security/Permission.php b/src/Security/Permission.php index c15757f575a..ce57f81bbf3 100644 --- a/src/Security/Permission.php +++ b/src/Security/Permission.php @@ -122,7 +122,7 @@ public static function check($code, $arg = "any", $member = null, $strict = true $member = Security::getCurrentUser(); } - return self::checkMember($member, $code, $arg, $strict); + return Permission::checkMember($member, $code, $arg, $strict); } /** @@ -136,7 +136,7 @@ public static function check($code, $arg = "any", $member = null, $strict = true */ public static function reset() { - self::$cache_permissions = []; + Permission::$cache_permissions = []; } /** @@ -173,12 +173,12 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) if ($arg == 'any') { // Cache the permissions in memory - if (!isset(self::$cache_permissions[$memberID])) { - self::$cache_permissions[$memberID] = self::permissions_for_member($memberID); + if (!isset(Permission::$cache_permissions[$memberID])) { + Permission::$cache_permissions[$memberID] = Permission::permissions_for_member($memberID); } foreach ($code as $permCode) { if ($permCode === 'CMS_ACCESS') { - foreach (self::$cache_permissions[$memberID] as $perm) { + foreach (Permission::$cache_permissions[$memberID] as $perm) { //if they have admin rights OR they have an explicit access to the CMS then give permission if (($adminImpliesAll && $perm == 'ADMIN') || substr($perm ?? '', 0, 11) === 'CMS_ACCESS_') { return true; @@ -196,7 +196,7 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) } // Multiple $code values - return true if at least one matches, ie, intersection exists - return (bool)array_intersect($code ?? [], self::$cache_permissions[$memberID]); + return (bool)array_intersect($code ?? [], Permission::$cache_permissions[$memberID]); } // Code filters @@ -207,7 +207,7 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) // The following code should only be used if you're not using the "any" arg. This is kind // of obsolete functionality and could possibly be deprecated. - $groupParams = self::groupList($memberID); + $groupParams = Permission::groupList($memberID); if (empty($groupParams)) { return false; } @@ -245,7 +245,7 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) array_merge( $codeParams, $adminParams, - [self::GRANT_PERMISSION], + [Permission::GRANT_PERMISSION], $groupParams, $argParams ) @@ -264,7 +264,7 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) \"Code\" IN ($codeClause) AND \"Type\" = ? )", - array_merge($codeParams, [self::GRANT_PERMISSION]) + array_merge($codeParams, [Permission::GRANT_PERMISSION]) )->value(); if (!$hasPermission) { @@ -283,7 +283,7 @@ public static function checkMember($member, $code, $arg = "any", $strict = true) */ public static function permissions_for_member($memberID) { - $groupList = self::groupList($memberID); + $groupList = Permission::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); @@ -291,7 +291,7 @@ public static function permissions_for_member($memberID) $allowed = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" - WHERE \"Type\" = " . self::GRANT_PERMISSION . " AND \"GroupID\" IN ($groupCSV) + WHERE \"Type\" = " . Permission::GRANT_PERMISSION . " AND \"GroupID\" IN ($groupCSV) UNION @@ -305,7 +305,7 @@ public static function permissions_for_member($memberID) $denied = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" - WHERE \"Type\" = " . self::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) + WHERE \"Type\" = " . Permission::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) ")->column() ?? []); return array_diff($allowed ?? [], $denied); @@ -384,7 +384,7 @@ public static function grant($groupID, $code, $arg = "any") $perm->Code = $code; } - $perm->Type = self::GRANT_PERMISSION; + $perm->Type = Permission::GRANT_PERMISSION; // Arg component switch ($arg) { @@ -426,7 +426,7 @@ public static function deny($groupID, $code, $arg = "any") $perm->Code = $code; } - $perm->Type = self::DENY_PERMISSION; + $perm->Type = Permission::DENY_PERMISSION; // Arg component switch ($arg) { @@ -456,7 +456,7 @@ public static function deny($groupID, $code, $arg = "any") */ public static function get_members_by_permission($code) { - $toplevelGroups = self::get_groups_by_permission($code); + $toplevelGroups = Permission::get_groups_by_permission($code); if (!$toplevelGroups) { return new ArrayList(); } diff --git a/src/Security/RememberLoginHash.php b/src/Security/RememberLoginHash.php index 27f9f345bad..389afcebded 100644 --- a/src/Security/RememberLoginHash.php +++ b/src/Security/RememberLoginHash.php @@ -217,9 +217,9 @@ public static function clear(Member $member, $alcDevice = null) } if (static::getLogoutAcrossDevices()) { - self::get()->filter(['MemberID' => $member->ID])->removeAll(); + RememberLoginHash::get()->filter(['MemberID' => $member->ID])->removeAll(); } elseif ($alcDevice) { - self::get()->filter([ + RememberLoginHash::get()->filter([ 'MemberID' => $member->ID, 'DeviceID' => $alcDevice ])->removeAll(); diff --git a/src/Security/Security.php b/src/Security/Security.php index eea203ba479..214dbcb47d8 100644 --- a/src/Security/Security.php +++ b/src/Security/Security.php @@ -306,7 +306,7 @@ public function hasAuthenticator($authenticator) */ public static function permissionFailure($controller = null, $messageSet = null): HTTPResponse { - self::set_ignore_disallowed_actions(true); + Security::set_ignore_disallowed_actions(true); // Parse raw message / escape type $parseMessage = function ($message) { @@ -437,7 +437,7 @@ public static function permissionFailure($controller = null, $messageSet = null) */ public static function setCurrentUser($currentUser = null) { - self::$currentUser = $currentUser; + Security::$currentUser = $currentUser; } /** @@ -445,7 +445,7 @@ public static function setCurrentUser($currentUser = null) */ public static function getCurrentUser() { - return self::$currentUser; + return Security::$currentUser; } /** @@ -1049,7 +1049,7 @@ public static function encrypt_password($password, $salt = null, $algorithm = nu { // Fall back to the default encryption algorithm if (!$algorithm) { - $algorithm = self::config()->get('password_encryption_algorithm'); + $algorithm = static::config()->get('password_encryption_algorithm'); } $encryptor = PasswordEncryptor::create_for_algorithm($algorithm); @@ -1074,12 +1074,12 @@ public static function encrypt_password($password, $salt = null, $algorithm = nu public static function database_is_ready() { // Used for unit tests - if (self::$force_database_is_ready !== null) { - return self::$force_database_is_ready; + if (Security::$force_database_is_ready !== null) { + return Security::$force_database_is_ready; } - if (self::$database_is_ready) { - return self::$database_is_ready; + if (Security::$database_is_ready) { + return Security::$database_is_ready; } $requiredClasses = ClassInfo::dataClassesFor(Member::class); @@ -1115,7 +1115,7 @@ public static function database_is_ready() return false; } } - self::$database_is_ready = true; + Security::$database_is_ready = true; return true; } @@ -1125,8 +1125,8 @@ public static function database_is_ready() */ public static function clear_database_is_ready() { - self::$database_is_ready = null; - self::$force_database_is_ready = null; + Security::$database_is_ready = null; + Security::$force_database_is_ready = null; } /** @@ -1136,7 +1136,7 @@ public static function clear_database_is_ready() */ public static function force_database_is_ready($isReady) { - self::$force_database_is_ready = $isReady; + Security::$force_database_is_ready = $isReady; } /** @@ -1165,12 +1165,12 @@ public static function force_database_is_ready($isReady) */ public static function set_ignore_disallowed_actions($flag) { - self::$ignore_disallowed_actions = $flag; + Security::$ignore_disallowed_actions = $flag; } public static function ignore_disallowed_actions() { - return self::$ignore_disallowed_actions; + return Security::$ignore_disallowed_actions; } /** @@ -1182,7 +1182,7 @@ public static function ignore_disallowed_actions() */ public static function login_url() { - return Controller::join_links(Director::baseURL(), self::config()->get('login_url')); + return Controller::join_links(Director::baseURL(), static::config()->get('login_url')); } @@ -1195,7 +1195,7 @@ public static function login_url() */ public static function logout_url() { - $logoutUrl = Controller::join_links(Director::baseURL(), self::config()->get('logout_url')); + $logoutUrl = Controller::join_links(Director::baseURL(), static::config()->get('logout_url')); return SecurityToken::inst()->addToUrl($logoutUrl); } @@ -1208,7 +1208,7 @@ public static function logout_url() */ public static function lost_password_url() { - return Controller::join_links(Director::baseURL(), self::config()->get('lost_password_url')); + return Controller::join_links(Director::baseURL(), static::config()->get('lost_password_url')); } /** diff --git a/src/Security/SecurityToken.php b/src/Security/SecurityToken.php index e6ba9c2f0e9..7c7ce6b9014 100644 --- a/src/Security/SecurityToken.php +++ b/src/Security/SecurityToken.php @@ -66,7 +66,7 @@ class SecurityToken implements TemplateGlobalProvider */ public function __construct($name = null) { - $this->name = $name ?: self::get_default_name(); + $this->name = $name ?: SecurityToken::get_default_name(); } /** @@ -76,11 +76,11 @@ public function __construct($name = null) */ public static function inst() { - if (!self::$inst) { - self::$inst = new SecurityToken(); + if (!SecurityToken::$inst) { + SecurityToken::$inst = new SecurityToken(); } - return self::$inst; + return SecurityToken::$inst; } /** @@ -89,8 +89,8 @@ public static function inst() */ public static function disable() { - self::$enabled = false; - self::$inst = new NullSecurityToken(); + SecurityToken::$enabled = false; + SecurityToken::$inst = new NullSecurityToken(); } /** @@ -98,8 +98,8 @@ public static function disable() */ public static function enable() { - self::$enabled = true; - self::$inst = new SecurityToken(); + SecurityToken::$enabled = true; + SecurityToken::$inst = new SecurityToken(); } /** @@ -107,7 +107,7 @@ public static function enable() */ public static function is_enabled() { - return self::$enabled; + return SecurityToken::$enabled; } /** @@ -115,7 +115,7 @@ public static function is_enabled() */ public static function get_default_name() { - return self::$default_name; + return SecurityToken::$default_name; } /** diff --git a/src/Security/SudoMode/SudoModeService.php b/src/Security/SudoMode/SudoModeService.php index 33deb10bf88..74fa8547fe4 100644 --- a/src/Security/SudoMode/SudoModeService.php +++ b/src/Security/SudoMode/SudoModeService.php @@ -27,7 +27,7 @@ class SudoModeService implements SudoModeServiceInterface public function check(Session $session): bool { - $lastActivated = $session->get(self::SUDO_MODE_SESSION_KEY); + $lastActivated = $session->get(SudoModeService::SUDO_MODE_SESSION_KEY); // Not activated at all if (!$lastActivated) { return false; @@ -41,7 +41,7 @@ public function check(Session $session): bool public function activate(Session $session): bool { - $session->set(self::SUDO_MODE_SESSION_KEY, DBDatetime::now()->getTimestamp()); + $session->set(SudoModeService::SUDO_MODE_SESSION_KEY, DBDatetime::now()->getTimestamp()); return true; } diff --git a/src/View/Embed/EmbedContainer.php b/src/View/Embed/EmbedContainer.php index 5ede0200f40..b7836cb4ab7 100644 --- a/src/View/Embed/EmbedContainer.php +++ b/src/View/Embed/EmbedContainer.php @@ -119,7 +119,7 @@ public function getOptions(): array return $this->options; } - public function setOptions(array $options): self + public function setOptions(array $options): EmbedContainer { $this->options = $options; return $this; diff --git a/src/View/Parsers/HtmlDiff.php b/src/View/Parsers/HtmlDiff.php index 2ee11e6b126..17ea1763911 100644 --- a/src/View/Parsers/HtmlDiff.php +++ b/src/View/Parsers/HtmlDiff.php @@ -31,21 +31,21 @@ public static function compareHtml(string|array $from, string|array $to, bool $e { // Get HTML chunks even if we're going to escape it later // The diff algorithm sees "some" as a single piece rather than "" and "some" being separate - $from = self::explodeToHtmlChunks($from); - $to = self::explodeToHtmlChunks($to); + $from = HtmlDiff::explodeToHtmlChunks($from); + $to = HtmlDiff::explodeToHtmlChunks($to); // Diff the chunks - $differ = self::getDiffer(); + $differ = HtmlDiff::getDiffer(); $diff = $differ->diffToArray($from, $to); // If we aren't escaping the HTML, convert the first diff into clean HTML blocks and then run a new diff // on the blocks to get an end result that doesn't have broken HTML if (!$escape) { - $diifAsBlocks = self::convertDiffToHtmlBlocks($diff); - $diff = $differ->diffToArray($diifAsBlocks[self::OLD_VAL], $diifAsBlocks[self::NEW_VAL]); + $diifAsBlocks = HtmlDiff::convertDiffToHtmlBlocks($diff); + $diff = $differ->diffToArray($diifAsBlocks[HtmlDiff::OLD_VAL], $diifAsBlocks[HtmlDiff::NEW_VAL]); } - $diff = self::createFinalDiffBlocks($diff, $escape); + $diff = HtmlDiff::createFinalDiffBlocks($diff, $escape); // Take the diff and slap the appropriate and tags in place $content = ''; @@ -76,7 +76,7 @@ public static function compareHtml(string|array $from, string|array $to, bool $e } } - return self::cleanHTML($content); + return HtmlDiff::cleanHTML($content); } /** @@ -94,7 +94,7 @@ private static function createFinalDiffBlocks(array $diff, bool $escaped): array foreach ($diff as $edit) { list($value, $type) = $edit; $isClosingTag = !$escaped && str_starts_with($value, ''); - $isOpeningNonVoidTag = !$escaped && self::isOpeningNonVoidTag($value); + $isOpeningNonVoidTag = !$escaped && HtmlDiff::isOpeningNonVoidTag($value); // If we were building a DIFFERENT type of block, or we've run out of open tags and are closing something // earlier in the chain, close the previous block and start a new one @@ -139,8 +139,8 @@ private static function createFinalDiffBlocks(array $diff, bool $escaped): array */ private static function convertDiffToHtmlBlocks(array $diff): array { - $openTagsInBlock[self::OLD_VAL] = $openTagsInBlock[self::NEW_VAL] = 0; - $htmlBlocks[self::OLD_VAL] = $htmlBlocks[self::NEW_VAL] = []; + $openTagsInBlock[HtmlDiff::OLD_VAL] = $openTagsInBlock[HtmlDiff::NEW_VAL] = 0; + $htmlBlocks[HtmlDiff::OLD_VAL] = $htmlBlocks[HtmlDiff::NEW_VAL] = []; foreach ($diff as $edit) { list($value, $type) = $edit; @@ -149,16 +149,16 @@ private static function convertDiffToHtmlBlocks(array $diff): array if ($value === '') { break; } - self::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, self::OLD_VAL, false, $value); - self::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, self::NEW_VAL, false, $value); + HtmlDiff::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, HtmlDiff::OLD_VAL, false, $value); + HtmlDiff::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, HtmlDiff::NEW_VAL, false, $value); break; case Differ::ADDED: - self::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, self::NEW_VAL, true, $value); + HtmlDiff::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, HtmlDiff::NEW_VAL, true, $value); break; case Differ::REMOVED: - self::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, self::OLD_VAL, true, $value); + HtmlDiff::addToHtmlBlocks($htmlBlocks, $openTagsInBlock, HtmlDiff::OLD_VAL, true, $value); break; } } @@ -186,7 +186,7 @@ private static function addToHtmlBlocks( $htmlBlocks[$oldOrNew][] = $value; } - if ($canAddTagsToBlock && self::isOpeningNonVoidTag($value)) { + if ($canAddTagsToBlock && HtmlDiff::isOpeningNonVoidTag($value)) { // If we're mid block or explicitly looking for new tags, we should add any new non-void tags to the block $openTagsInBlock[$oldOrNew]++; } elseif ($alreadyMidBlock && str_starts_with($value, '')) { @@ -254,13 +254,13 @@ private static function explodeToHtmlChunks(string|array $content): array * This cleans code if possible, using an instance of HTMLCleaner * * @param ?HTMLCleaner $cleaner Optional instance of a HTMLCleaner class to - * use, overriding self::$html_cleaner_class + * use, overriding HtmlDiff::$html_cleaner_class */ private static function cleanHTML(string $content, ?HTMLCleaner $cleaner = null): string { if (!$cleaner) { - if (self::$html_cleaner_class && class_exists(self::$html_cleaner_class)) { - $cleaner = Injector::inst()->create(self::$html_cleaner_class); + if (HtmlDiff::$html_cleaner_class && class_exists(HtmlDiff::$html_cleaner_class)) { + $cleaner = Injector::inst()->create(HtmlDiff::$html_cleaner_class); } else { //load cleaner if the dependent class is available $cleaner = HTMLCleaner::inst(); @@ -284,9 +284,9 @@ private static function cleanHTML(string $content, ?HTMLCleaner $cleaner = null) private static function getDiffer(): Differ { - if (!self::$differ) { - self::$differ = new Differ(); + if (!HtmlDiff::$differ) { + HtmlDiff::$differ = new Differ(); } - return self::$differ; + return HtmlDiff::$differ; } } diff --git a/src/View/Parsers/SQLFormatter.php b/src/View/Parsers/SQLFormatter.php index fefc024a4e0..4a73556a2c5 100644 --- a/src/View/Parsers/SQLFormatter.php +++ b/src/View/Parsers/SQLFormatter.php @@ -58,7 +58,7 @@ public function formatHTML($sql) protected function addNewlines($sql, $useHtmlFormatting = false) { $eol = PHP_EOL; - foreach (self::$newline_before_tokens as $token) { + foreach (SQLFormatter::$newline_before_tokens as $token) { $breakToken = ($useHtmlFormatting) ? "
$eol" : $eol; $sql = preg_replace('/[^\n](' . $token . ')/', $breakToken . '$1', $sql ?? ''); } diff --git a/src/View/Parsers/ShortcodeParser.php b/src/View/Parsers/ShortcodeParser.php index 1032c862af0..2031a1645f8 100644 --- a/src/View/Parsers/ShortcodeParser.php +++ b/src/View/Parsers/ShortcodeParser.php @@ -58,11 +58,11 @@ public function img_shortcode($attrs) */ public static function get($identifier = 'default') { - if (!array_key_exists($identifier, self::$instances)) { - self::$instances[$identifier] = static::create(); + if (!array_key_exists($identifier, ShortcodeParser::$instances)) { + ShortcodeParser::$instances[$identifier] = static::create(); } - return self::$instances[$identifier]; + return ShortcodeParser::$instances[$identifier]; } /** @@ -72,7 +72,7 @@ public static function get($identifier = 'default') */ public static function get_active() { - return static::get(self::$active_instance); + return static::get(ShortcodeParser::$active_instance); } /** @@ -82,7 +82,7 @@ public static function get_active() */ public static function set_active($identifier) { - self::$active_instance = (string) $identifier; + ShortcodeParser::$active_instance = (string) $identifier; } // -------------------------------------------------------------------------------------------------------------- @@ -192,7 +192,7 @@ public function getShortcodeReplacementText($tag, $extra = [], $isHTMLAllowed = if ($content === false) { if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { throw new \InvalidArgumentException('Unknown shortcode tag ' . $tag['open']); - } elseif (self::$error_behavior == self::WARN && $isHTMLAllowed) { + } elseif (ShortcodeParser::$error_behavior == ShortcodeParser::WARN && $isHTMLAllowed) { $content = '' . $tag['text'] . ''; } elseif (ShortcodeParser::$error_behavior == ShortcodeParser::STRIP) { return ''; @@ -271,7 +271,7 @@ protected function insertListAfter($new, $after) protected static function attrrx() { - return '/' . self::$attrrx . '/xS'; + return '/' . ShortcodeParser::$attrrx . '/xS'; } protected static $tagrx = ' @@ -296,7 +296,7 @@ protected static function attrrx() protected static function tagrx() { - return '/' . sprintf(self::$tagrx, self::$attrrx) . '/xS'; + return '/' . sprintf(ShortcodeParser::$tagrx, ShortcodeParser::$attrrx) . '/xS'; } const WARN = 'warn'; @@ -304,7 +304,7 @@ protected static function tagrx() const LEAVE = 'leave'; const ERROR = 'error'; - public static $error_behavior = self::LEAVE; + public static $error_behavior = ShortcodeParser::LEAVE; /** @@ -380,7 +380,7 @@ public function extractTags($content) } if ($err) { - if (self::$error_behavior == self::ERROR) { + if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { throw new \Exception($err); } } else { @@ -407,9 +407,9 @@ public function extractTags($content) } // Step 3: remove any tags that don't have handlers registered - // Only do this if self::$error_behavior == self::LEAVE + // Only do this if ShortcodeParser::$error_behavior == ShortcodeParser::LEAVE // This is optional but speeds things up. - if (self::$error_behavior == self::LEAVE) { + if (ShortcodeParser::$error_behavior == ShortcodeParser::LEAVE) { foreach ($tags as $i => $tag) { if (empty($this->shortcodes[$tag['open']])) { unset($tags[$i]); @@ -497,7 +497,7 @@ protected function replaceElementTagsWithMarkers($content) $tags = $this->extractTags($content); if ($tags) { - $markerClass = self::$marker_class; + $markerClass = ShortcodeParser::$marker_class; $content = $this->replaceTagsWithText($content, $tags, function ($idx, $tag) use ($markerClass) { return ''; @@ -522,7 +522,7 @@ protected function findParentsForMarkers($nodes) do { $parent = $parent->parentNode; } while ($parent instanceof DOMElement && - !in_array(strtolower($parent->tagName ?? ''), self::$block_level_elements) + !in_array(strtolower($parent->tagName ?? ''), ShortcodeParser::$block_level_elements) ); $node->setAttribute('data-parentid', count($parents ?? [])); @@ -566,14 +566,14 @@ protected function findParentsForMarkers($nodes) protected function moveMarkerToCompliantHome($node, $parent, $location) { // Move before block parent - if ($location == self::BEFORE) { + if ($location == ShortcodeParser::BEFORE) { if (isset($parent->parentNode)) { $parent->parentNode->insertBefore($node, $parent); } - } elseif ($location == self::AFTER) { + } elseif ($location == ShortcodeParser::AFTER) { // Move after block parent $this->insertAfter($node, $parent); - } elseif ($location == self::SPLIT) { + } elseif ($location == ShortcodeParser::SPLIT) { // Split parent at node $at = $node; $splitee = $node->parentNode; @@ -593,9 +593,9 @@ protected function moveMarkerToCompliantHome($node, $parent, $location) } $this->insertAfter($node, $parent); - } elseif ($location == self::INLINE) { + } elseif ($location == ShortcodeParser::INLINE) { // Do nothing - if (in_array(strtolower($node->tagName ?? ''), self::$block_level_elements)) { + if (in_array(strtolower($node->tagName ?? ''), ShortcodeParser::$block_level_elements)) { user_error( 'Requested to insert block tag ' . $node->tagName . ' inline - probably this will break HTML compliance', E_USER_WARNING @@ -661,7 +661,7 @@ public function parse($content) // Now parse the result into a DOM if (!$htmlvalue->isValid()) { - if (self::$error_behavior == self::ERROR) { + if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { throw new \Exception('Couldn\'t decode HTML when processing short codes'); } else { $continue = false; @@ -674,7 +674,7 @@ public function parse($content) $this->replaceAttributeTagsWithContent($htmlvalue); // Find all the element scoped shortcode markers - $shortcodes = $htmlvalue->query('//img[@class="' . self::$marker_class . '"]'); + $shortcodes = $htmlvalue->query('//img[@class="' . ShortcodeParser::$marker_class . '"]'); // Find the parents. Do this before DOM modification, since SPLIT might cause parents to move otherwise $parents = $this->findParentsForMarkers($shortcodes); @@ -691,19 +691,19 @@ public function parse($content) $class = $tag['attrs']['class']; } - $location = self::INLINE; + $location = ShortcodeParser::INLINE; if ($class == 'left' || $class == 'right') { - $location = self::BEFORE; + $location = ShortcodeParser::BEFORE; } /** * Below code disabled due to https://github.com/silverstripe/silverstripe-framework/issues/5987 if ($class == 'center' || $class == 'leftAlone') { - $location = self::SPLIT; + $location = ShortcodeParser::SPLIT; } */ if (!$parent) { - if ($location !== self::INLINE) { + if ($location !== ShortcodeParser::INLINE) { throw new \RuntimeException( "Parent block for shortcode couldn't be found, but location wasn't INLINE" ); @@ -722,7 +722,7 @@ public function parse($content) $content = preg_replace_callback( // Not a general-case parser; assumes that the HTML generated in replaceElementTagsWithMarkers() // hasn't been heavily modified - '/]+class="' . preg_quote(self::$marker_class) . '"[^>]+data-tagid="([^"]+)"[^>]*>/i', + '/]+class="' . preg_quote(ShortcodeParser::$marker_class) . '"[^>]+data-tagid="([^"]+)"[^>]*>/i', function ($matches) use ($tags, $parser) { $tag = $tags[$matches[1]]; return $parser->getShortcodeReplacementText($tag); diff --git a/src/View/Requirements.php b/src/View/Requirements.php index c757f2ba2d9..0656d26dd43 100644 --- a/src/View/Requirements.php +++ b/src/View/Requirements.php @@ -31,7 +31,7 @@ public static function flush() { $disabled = Config::inst()->get(static::class, 'disable_flush_combined'); if (!$disabled) { - self::delete_all_combined_files(); + Requirements::delete_all_combined_files(); } } @@ -42,7 +42,7 @@ public static function flush() */ public static function set_combined_files_enabled($enable) { - self::backend()->setCombinedFilesEnabled($enable); + Requirements::backend()->setCombinedFilesEnabled($enable); } /** @@ -52,7 +52,7 @@ public static function set_combined_files_enabled($enable) */ public static function get_combined_files_enabled() { - return self::backend()->getCombinedFilesEnabled(); + return Requirements::backend()->getCombinedFilesEnabled(); } /** @@ -62,7 +62,7 @@ public static function get_combined_files_enabled() */ public static function set_combined_files_folder($folder) { - self::backend()->setCombinedFilesFolder($folder); + Requirements::backend()->setCombinedFilesFolder($folder); } /** @@ -75,7 +75,7 @@ public static function set_combined_files_folder($folder) */ public static function set_suffix_requirements($var) { - self::backend()->setSuffixRequirements($var); + Requirements::backend()->setSuffixRequirements($var); } /** @@ -85,7 +85,7 @@ public static function set_suffix_requirements($var) */ public static function get_suffix_requirements() { - return self::backend()->getSuffixRequirements(); + return Requirements::backend()->getSuffixRequirements(); } /** @@ -101,10 +101,10 @@ public static function get_suffix_requirements() */ public static function backend() { - if (!self::$backend) { - self::$backend = Requirements_Backend::create(); + if (!Requirements::$backend) { + Requirements::$backend = Requirements_Backend::create(); } - return self::$backend; + return Requirements::$backend; } /** @@ -114,7 +114,7 @@ public static function backend() */ public static function set_backend(Requirements_Backend $backend) { - self::$backend = $backend; + Requirements::$backend = $backend; } /** @@ -128,7 +128,7 @@ public static function set_backend(Requirements_Backend $backend) */ public static function javascript($file, $options = []) { - self::backend()->javascript($file, $options); + Requirements::backend()->javascript($file, $options); } /** @@ -139,7 +139,7 @@ public static function javascript($file, $options = []) */ public static function customScript($script, $uniquenessID = null) { - self::backend()->customScript($script, $uniquenessID); + Requirements::backend()->customScript($script, $uniquenessID); } /** @@ -154,7 +154,7 @@ public static function customScript($script, $uniquenessID = null) */ public static function customScriptWithAttributes(string $script, array $options = [], string|int|null $uniquenessID = null) { - self::backend()->customScriptWithAttributes($script, $options, $uniquenessID); + Requirements::backend()->customScriptWithAttributes($script, $options, $uniquenessID); } /** @@ -164,7 +164,7 @@ public static function customScriptWithAttributes(string $script, array $options */ public static function get_custom_scripts() { - return self::backend()->getCustomScripts(); + return Requirements::backend()->getCustomScripts(); } /** @@ -175,7 +175,7 @@ public static function get_custom_scripts() */ public static function customCSS($script, $uniquenessID = null) { - self::backend()->customCSS($script, $uniquenessID); + Requirements::backend()->customCSS($script, $uniquenessID); } /** @@ -186,7 +186,7 @@ public static function customCSS($script, $uniquenessID = null) */ public static function insertHeadTags($html, $uniquenessID = null) { - self::backend()->insertHeadTags($html, $uniquenessID); + Requirements::backend()->insertHeadTags($html, $uniquenessID); } /** @@ -199,7 +199,7 @@ public static function insertHeadTags($html, $uniquenessID = null) */ public static function javascriptTemplate($file, $vars, $uniquenessID = null) { - self::backend()->javascriptTemplate($file, $vars, $uniquenessID); + Requirements::backend()->javascriptTemplate($file, $vars, $uniquenessID); } /** @@ -214,7 +214,7 @@ public static function javascriptTemplate($file, $vars, $uniquenessID = null) */ public static function css($file, $media = null, $options = []) { - self::backend()->css($file, $media, $options); + Requirements::backend()->css($file, $media, $options); } /** @@ -230,7 +230,7 @@ public static function css($file, $media = null, $options = []) */ public static function themedCSS($name, $media = null) { - self::backend()->themedCSS($name, $media); + Requirements::backend()->themedCSS($name, $media); } /** @@ -246,7 +246,7 @@ public static function themedCSS($name, $media = null) */ public static function themedJavascript($name, $type = null) { - self::backend()->themedJavascript($name, $type); + Requirements::backend()->themedJavascript($name, $type); } /** @@ -259,7 +259,7 @@ public static function themedJavascript($name, $type = null) */ public static function clear($fileOrID = null) { - self::backend()->clear($fileOrID); + Requirements::backend()->clear($fileOrID); } /** @@ -267,7 +267,7 @@ public static function clear($fileOrID = null) */ public static function restore() { - self::backend()->restore(); + Requirements::backend()->restore(); } /** @@ -285,7 +285,7 @@ public static function restore() */ public static function block($fileOrID) { - self::backend()->block($fileOrID); + Requirements::backend()->block($fileOrID); } /** @@ -295,7 +295,7 @@ public static function block($fileOrID) */ public static function unblock($fileOrID) { - self::backend()->unblock($fileOrID); + Requirements::backend()->unblock($fileOrID); } /** @@ -303,7 +303,7 @@ public static function unblock($fileOrID) */ public static function unblock_all() { - self::backend()->unblockAll(); + Requirements::backend()->unblockAll(); } /** @@ -317,7 +317,7 @@ public static function unblock_all() */ public static function includeInHTML($content) { - return self::backend()->includeInHTML($content); + return Requirements::backend()->includeInHTML($content); } /** @@ -328,7 +328,7 @@ public static function includeInHTML($content) */ public static function include_in_response(HTTPResponse $response) { - self::backend()->includeInResponse($response); + Requirements::backend()->includeInResponse($response); } /** @@ -345,7 +345,7 @@ public static function include_in_response(HTTPResponse $response) */ public static function add_i18n_javascript($langDir, $return = false) { - return self::backend()->add_i18n_javascript($langDir, $return); + return Requirements::backend()->add_i18n_javascript($langDir, $return); } /** @@ -399,7 +399,7 @@ public static function combine_files($combinedFileName, $files, $options = []) if (is_string($options)) { throw new InvalidArgumentException("Invalid $options"); } - self::backend()->combineFiles($combinedFileName, $files, $options); + Requirements::backend()->combineFiles($combinedFileName, $files, $options); } /** @@ -411,7 +411,7 @@ public static function combine_files($combinedFileName, $files, $options = []) */ public static function get_combine_files() { - return self::backend()->getCombinedFiles(); + return Requirements::backend()->getCombinedFiles(); } /** @@ -420,7 +420,7 @@ public static function get_combine_files() */ public static function delete_all_combined_files() { - self::backend()->deleteAllCombinedFiles(); + Requirements::backend()->deleteAllCombinedFiles(); } /** @@ -428,7 +428,7 @@ public static function delete_all_combined_files() */ public static function clear_combined_files() { - self::backend()->clearCombinedFiles(); + Requirements::backend()->clearCombinedFiles(); } /** @@ -436,7 +436,7 @@ public static function clear_combined_files() */ public static function process_combined_files() { - self::backend()->processCombinedFiles(); + Requirements::backend()->processCombinedFiles(); } /** @@ -447,7 +447,7 @@ public static function process_combined_files() */ public static function get_write_js_to_body() { - return self::backend()->getWriteJavascriptToBody(); + return Requirements::backend()->getWriteJavascriptToBody(); } /** @@ -458,7 +458,7 @@ public static function get_write_js_to_body() */ public static function set_write_js_to_body($var) { - self::backend()->setWriteJavascriptToBody($var); + Requirements::backend()->setWriteJavascriptToBody($var); } /** @@ -469,7 +469,7 @@ public static function set_write_js_to_body($var) */ public static function get_force_js_to_bottom() { - return self::backend()->getForceJSToBottom(); + return Requirements::backend()->getForceJSToBottom(); } /** @@ -480,7 +480,7 @@ public static function get_force_js_to_bottom() */ public static function set_force_js_to_bottom($var) { - self::backend()->setForceJSToBottom($var); + Requirements::backend()->setForceJSToBottom($var); } /** @@ -490,7 +490,7 @@ public static function set_force_js_to_bottom($var) */ public static function get_minify_combined_js_files() { - return self::backend()->getMinifyCombinedJSFiles(); + return Requirements::backend()->getMinifyCombinedJSFiles(); } /** @@ -500,7 +500,7 @@ public static function get_minify_combined_js_files() */ public static function set_minify_combined_js_files($minify) { - self::backend()->setMinifyCombinedJSFiles($minify); + Requirements::backend()->setMinifyCombinedJSFiles($minify); } /** @@ -510,7 +510,7 @@ public static function set_minify_combined_js_files($minify) */ public static function get_write_header_comments() { - return self::backend()->getWriteHeaderComment(); + return Requirements::backend()->getWriteHeaderComment(); } /** @@ -520,7 +520,7 @@ public static function get_write_header_comments() */ public function set_write_header_comments($write) { - self::backend()->setWriteHeaderComment($write); + Requirements::backend()->setWriteHeaderComment($write); } @@ -529,6 +529,6 @@ public function set_write_header_comments($write) */ public static function debug() { - self::backend()->debug(); + Requirements::backend()->debug(); } } diff --git a/src/View/SSViewer.php b/src/View/SSViewer.php index c74766515d3..3b82eb3fdd9 100644 --- a/src/View/SSViewer.php +++ b/src/View/SSViewer.php @@ -194,7 +194,7 @@ public function __construct($templates, TemplateParser $parser = null) $message = 'None of the following templates could be found: '; $message .= print_r($templates, true); - $themes = self::get_themes(); + $themes = SSViewer::get_themes(); if (!$themes) { $message .= ' (no theme in use)'; } else { @@ -210,8 +210,8 @@ public function __construct($templates, TemplateParser $parser = null) */ public static function flush() { - self::flush_template_cache(true); - self::flush_cacheblock_cache(true); + SSViewer::flush_template_cache(true); + SSViewer::flush_cacheblock_cache(true); } /** @@ -261,7 +261,7 @@ public static function add_themes($themes = []) */ public static function get_themes() { - $default = [self::PUBLIC_THEME, self::DEFAULT_THEME]; + $default = [SSViewer::PUBLIC_THEME, SSViewer::DEFAULT_THEME]; if (!SSViewer::config()->uninherited('theme_enabled')) { return $default; @@ -401,7 +401,7 @@ public function setTemplate($templates) */ public static function chooseTemplate($templates) { - return ThemeResourceLoader::inst()->findTemplate($templates, self::get_themes()); + return ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes()); } /** @@ -436,7 +436,7 @@ public function getParser() */ public static function hasTemplate($templates) { - return (bool)ThemeResourceLoader::inst()->findTemplate($templates, self::get_themes()); + return (bool)ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes()); } /** @@ -465,7 +465,7 @@ public function exists() */ public static function getTemplateFileByType($identifier, $type = null) { - return ThemeResourceLoader::inst()->findTemplate(['type' => $type, $identifier], self::get_themes()); + return ThemeResourceLoader::inst()->findTemplate(['type' => $type, $identifier], SSViewer::get_themes()); } /** @@ -478,14 +478,14 @@ public static function getTemplateFileByType($identifier, $type = null) */ public static function flush_template_cache($force = false) { - if (!self::$template_cache_flushed || $force) { + if (!SSViewer::$template_cache_flushed || $force) { $dir = dir(TEMP_PATH); while (false !== ($file = $dir->read())) { if (strstr($file ?? '', '.cache')) { unlink(TEMP_PATH . DIRECTORY_SEPARATOR . $file); } } - self::$template_cache_flushed = true; + SSViewer::$template_cache_flushed = true; } } @@ -499,12 +499,12 @@ public static function flush_template_cache($force = false) */ public static function flush_cacheblock_cache($force = false) { - if (!self::$cacheblock_cache_flushed || $force) { + if (!SSViewer::$cacheblock_cache_flushed || $force) { $cache = Injector::inst()->get(CacheInterface::class . '.cacheblock'); $cache->clear(); - self::$cacheblock_cache_flushed = true; + SSViewer::$cacheblock_cache_flushed = true; } } diff --git a/src/View/SSViewer_DataPresenter.php b/src/View/SSViewer_DataPresenter.php index 9a65d01fae7..a72f5051b27 100644 --- a/src/View/SSViewer_DataPresenter.php +++ b/src/View/SSViewer_DataPresenter.php @@ -79,11 +79,11 @@ public function __construct( */ protected function cacheGlobalProperties() { - if (self::$globalProperties !== null) { + if (SSViewer_DataPresenter::$globalProperties !== null) { return; } - self::$globalProperties = $this->getPropertiesFromProvider( + SSViewer_DataPresenter::$globalProperties = $this->getPropertiesFromProvider( TemplateGlobalProvider::class, 'get_template_global_variables' ); @@ -94,11 +94,11 @@ protected function cacheGlobalProperties() */ protected function cacheIteratorProperties() { - if (self::$iteratorProperties !== null) { + if (SSViewer_DataPresenter::$iteratorProperties !== null) { return; } - self::$iteratorProperties = $this->getPropertiesFromProvider( + SSViewer_DataPresenter::$iteratorProperties = $this->getPropertiesFromProvider( TemplateIteratorProvider::class, 'get_template_iterator_variables', true // Call non-statically @@ -388,8 +388,8 @@ protected function getValueSource($property) } // Then for iterator-specific overrides - if (array_key_exists($property, self::$iteratorProperties)) { - $source = self::$iteratorProperties[$property]; + if (array_key_exists($property, SSViewer_DataPresenter::$iteratorProperties)) { + $source = SSViewer_DataPresenter::$iteratorProperties[$property]; /** @var TemplateIteratorProvider $implementor */ $implementor = $source['implementor']; if ($this->itemIterator) { @@ -408,9 +408,9 @@ protected function getValueSource($property) } // And finally for global overrides - if (array_key_exists($property, self::$globalProperties)) { + if (array_key_exists($property, SSViewer_DataPresenter::$globalProperties)) { return [ - 'source' => self::$globalProperties[$property] // get the method call + 'source' => SSViewer_DataPresenter::$globalProperties[$property] // get the method call ]; } diff --git a/src/View/SSViewer_Scope.php b/src/View/SSViewer_Scope.php index aa4ee206557..f82b84062d8 100644 --- a/src/View/SSViewer_Scope.php +++ b/src/View/SSViewer_Scope.php @@ -127,7 +127,7 @@ public function getItem() /** * Called at the start of every lookup chain by SSTemplateParser to indicate a new lookup from local scope * - * @return self + * @return SSViewer_Scope */ public function locally() { @@ -249,7 +249,7 @@ public function self() /** * Jump to the last item in the stack, called when a new item is added before a loop/with * - * @return self + * @return SSViewer_Scope */ public function pushScope() { @@ -271,7 +271,7 @@ public function pushScope() /** * Jump back to "previous" item in the stack, called after a loop/with block * - * @return self + * @return SSViewer_Scope */ public function popScope() { diff --git a/src/View/Shortcodes/EmbedShortcodeProvider.php b/src/View/Shortcodes/EmbedShortcodeProvider.php index 9a8c524506f..89806d6bc26 100644 --- a/src/View/Shortcodes/EmbedShortcodeProvider.php +++ b/src/View/Shortcodes/EmbedShortcodeProvider.php @@ -200,7 +200,7 @@ protected static function videoEmbed($arguments, $content) 'Content' => DBField::create_field('HTMLFragment', $content) ]; - return ArrayData::create($data)->renderWith(self::class . '_video')->forTemplate(); + return ArrayData::create($data)->renderWith(EmbedShortcodeProvider::class . '_video')->forTemplate(); } /** @@ -220,7 +220,7 @@ protected static function linkEmbed($arguments, $href, $title) 'Title' => !empty($arguments['caption']) ? ($arguments['caption']) : $title ]; - return ArrayData::create($data)->renderWith(self::class . '_link')->forTemplate(); + return ArrayData::create($data)->renderWith(EmbedShortcodeProvider::class . '_link')->forTemplate(); } /** @@ -238,7 +238,7 @@ protected static function photoEmbed($arguments, $src) 'Src' => $src ]; - return ArrayData::create($data)->renderWith(self::class . '_photo')->forTemplate(); + return ArrayData::create($data)->renderWith(EmbedShortcodeProvider::class . '_photo')->forTemplate(); } /** @@ -327,10 +327,10 @@ private static function deriveCacheKey(string $url, string $class, string $width { return implode('-', array_filter([ 'embed-shortcode', - self::cleanKeySegment($url), - self::cleanKeySegment($class), - self::cleanKeySegment($width), - self::cleanKeySegment($height) + EmbedShortcodeProvider::cleanKeySegment($url), + EmbedShortcodeProvider::cleanKeySegment($class), + EmbedShortcodeProvider::cleanKeySegment($width), + EmbedShortcodeProvider::cleanKeySegment($height) ])); } diff --git a/src/View/ThemeManifest.php b/src/View/ThemeManifest.php index f764d71a1b1..402ac4aa6b5 100644 --- a/src/View/ThemeManifest.php +++ b/src/View/ThemeManifest.php @@ -161,7 +161,7 @@ public function regenerate($includeTests = false) */ public function handleDirectory($basename, $pathname, $depth) { - if ($basename !== self::TEMPLATES_DIR) { + if ($basename !== ThemeManifest::TEMPLATES_DIR) { return; } $dir = trim(substr(dirname($pathname ?? ''), strlen($this->base ?? '')), '/\\'); diff --git a/src/View/ThemeResourceLoader.php b/src/View/ThemeResourceLoader.php index 7967c22bdac..8799fe13a66 100644 --- a/src/View/ThemeResourceLoader.php +++ b/src/View/ThemeResourceLoader.php @@ -46,7 +46,7 @@ class ThemeResourceLoader implements Flushable, TemplateGlobalProvider */ public static function inst() { - return self::$instance ? self::$instance : self::$instance = new self(); + return ThemeResourceLoader::$instance ? ThemeResourceLoader::$instance : ThemeResourceLoader::$instance = new ThemeResourceLoader(); } /** @@ -56,7 +56,7 @@ public static function inst() */ public static function set_instance(ThemeResourceLoader $instance) { - self::$instance = $instance; + ThemeResourceLoader::$instance = $instance; } public function __construct($base = null) @@ -390,7 +390,7 @@ public function getThemePaths($themes = null) */ public static function flush() { - self::inst()->getCache()->clear(); + ThemeResourceLoader::inst()->getCache()->clear(); } /** diff --git a/src/View/ViewableData.php b/src/View/ViewableData.php index f5f19ec8c0f..d729d36da72 100644 --- a/src/View/ViewableData.php +++ b/src/View/ViewableData.php @@ -267,7 +267,7 @@ private function isAccessibleMethod(string $method): bool return $this->hasCustomMethod($method); } // All methods defined on ViewableData are accessible to ViewableData - if (static::class === self::class) { + if (static::class === ViewableData::class) { return true; } // Private methods defined on subclasses are not accessible to ViewableData @@ -284,7 +284,7 @@ private function isAccessibleProperty(string $property): bool if (!property_exists($this, $property)) { return false; } - if (static::class === self::class) { + if (static::class === ViewableData::class) { return true; } $reflectionProperty = new ReflectionProperty($this, $property); @@ -665,7 +665,7 @@ public function getIterator(): Traversable */ public function getViewerTemplates($suffix = '') { - return SSViewer::get_templates_by_class(static::class, $suffix, self::class); + return SSViewer::get_templates_by_class(static::class, $suffix, ViewableData::class); } /** @@ -689,7 +689,7 @@ public function Me() * @return string * @uses ClassInfo */ - public function CSSClasses($stopAtClass = self::class) + public function CSSClasses($stopAtClass = ViewableData::class) { $classes = []; $classAncestry = array_reverse(ClassInfo::ancestry(static::class) ?? []); diff --git a/src/i18n/TextCollection/i18nTextCollector.php b/src/i18n/TextCollection/i18nTextCollector.php index fce88716dea..3d3d6fa6f8f 100644 --- a/src/i18n/TextCollection/i18nTextCollector.php +++ b/src/i18n/TextCollection/i18nTextCollector.php @@ -474,7 +474,7 @@ private function getModulesAndThemes(): array if (!empty($themes)) { foreach ($themes as $theme) { if (is_dir(Path::join(THEMES_PATH, $theme))) { - $modules[self::THEME_PREFIX . $theme] = new Module(Path::join(THEMES_PATH, $theme), BASE_PATH); + $modules[i18nTextCollector::THEME_PREFIX . $theme] = new Module(Path::join(THEMES_PATH, $theme), BASE_PATH); } } } @@ -488,7 +488,7 @@ private function getModulesAndThemes(): array */ private function getModuleName(string $origName, Module $module): string { - return strpos($origName, self::THEME_PREFIX) === 0 ? $origName : $module->getName(); + return strpos($origName, i18nTextCollector::THEME_PREFIX) === 0 ? $origName : $module->getName(); } /** @@ -558,7 +558,7 @@ protected function getFileListForModule(Module $module) $modulePath = $module->getPath(); // Search all .ss files in themes - if (stripos($module->getRelativePath() ?? '', self::THEME_PREFIX) === 0) { + if (stripos($module->getRelativePath() ?? '', i18nTextCollector::THEME_PREFIX) === 0) { return $this->getFilesRecursive($modulePath, null, 'ss'); } @@ -608,7 +608,7 @@ public function collectFromCode($content, $fileName, Module $module) $inClass = false; // after `class` but before `{` $inUse = false; // pulling in classes from other namespaces $inArrayClosedBy = false; // Set to the expected closing token, or false if not in array - $inSelf = false; // Tracks progress of collecting self::class + $inSelf = false; // Tracks progress of collecting i18nTextCollector::class $currentEntity = []; $currentNameSpace = []; // The actual namespace for the current class $currentClass = []; // Class components @@ -677,7 +677,7 @@ public function collectFromCode($content, $fileName, Module $module) // Skip if previous token was '::'. E.g. 'Object::class' if (is_array($previousToken) && $previousToken[0] === T_DOUBLE_COLON) { if ($inSelf) { - // Handle self::class by allowing logic further down + // Handle i18nTextCollector::class by allowing logic further down // for __CLASS__/__TRAIT__ to handle an array of class parts $id = $id === T_TRAIT ? T_TRAIT_C : T_CLASS_C; $inSelf = false; @@ -741,7 +741,7 @@ public function collectFromCode($content, $fileName, Module $module) continue; } - // Start collecting self::class declarations + // Start collecting i18nTextCollector::class declarations if ($id === T_STRING && $text === 'self') { $inSelf = true; continue; @@ -770,7 +770,7 @@ function ($input) { throw new LogicException("Invalid string escape: " . $text); } } elseif ($id === T_CLASS_C || $id === T_TRAIT_C) { - // Evaluate __CLASS__ . '.KEY' and self::class concatenation + // Evaluate __CLASS__ . '.KEY' and i18nTextCollector::class concatenation $text = implode('\\', $currentClass); } else { continue; diff --git a/src/i18n/i18n.php b/src/i18n/i18n.php index 5f0b6f3f94e..61ab1ec159b 100644 --- a/src/i18n/i18n.php +++ b/src/i18n/i18n.php @@ -264,7 +264,7 @@ public static function encode_plurals($plurals) public static function get_closest_translation($locale) { // Check if exact match - $pool = self::getSources()->getKnownLocales(); + $pool = i18n::getSources()->getKnownLocales(); if (isset($pool[$locale])) { return $locale; } @@ -308,7 +308,7 @@ public static function convert_rfc1766($locale) public static function set_locale($locale) { if ($locale) { - self::$current_locale = $locale; + i18n::$current_locale = $locale; } } @@ -321,7 +321,7 @@ public static function set_locale($locale) */ public static function with_locale($locale, $callback) { - $oldLocale = self::$current_locale; + $oldLocale = i18n::$current_locale; static::set_locale($locale); try { return $callback(); @@ -338,10 +338,10 @@ public static function with_locale($locale, $callback) */ public static function get_locale() { - if (!self::$current_locale) { - self::$current_locale = i18n::config()->uninherited('default_locale'); + if (!i18n::$current_locale) { + i18n::$current_locale = i18n::config()->uninherited('default_locale'); } - return self::$current_locale; + return i18n::$current_locale; } /** diff --git a/tests/php/Control/FlushMiddlewareTest/TestFlushable.php b/tests/php/Control/FlushMiddlewareTest/TestFlushable.php index 7a28aa6ba68..f1c290e1651 100644 --- a/tests/php/Control/FlushMiddlewareTest/TestFlushable.php +++ b/tests/php/Control/FlushMiddlewareTest/TestFlushable.php @@ -11,6 +11,6 @@ class TestFlushable implements Flushable, TestOnly public static function flush() { - self::$flushed = true; + TestFlushable::$flushed = true; } } diff --git a/tests/php/Control/RSS/RSSFeedTest.php b/tests/php/Control/RSS/RSSFeedTest.php index b9150f29d5e..8392dd49599 100644 --- a/tests/php/Control/RSS/RSSFeedTest.php +++ b/tests/php/Control/RSS/RSSFeedTest.php @@ -100,8 +100,8 @@ protected function setUp(): void { parent::setUp(); Config::modify()->set(Director::class, 'alternate_base_url', '/'); - if (!self::$original_host) { - self::$original_host = $_SERVER['HTTP_HOST']; + if (!RSSFeedTest::$original_host) { + RSSFeedTest::$original_host = $_SERVER['HTTP_HOST']; } $_SERVER['HTTP_HOST'] = 'www.example.org'; @@ -116,6 +116,6 @@ function () { protected function tearDown(): void { parent::tearDown(); - $_SERVER['HTTP_HOST'] = self::$original_host; + $_SERVER['HTTP_HOST'] = RSSFeedTest::$original_host; } } diff --git a/tests/php/Control/RequestHandlingTest/ControllerExtension.php b/tests/php/Control/RequestHandlingTest/ControllerExtension.php index 44c849a5118..089e43a16a6 100644 --- a/tests/php/Control/RequestHandlingTest/ControllerExtension.php +++ b/tests/php/Control/RequestHandlingTest/ControllerExtension.php @@ -27,7 +27,7 @@ public function extendedMethod() */ public function onBeforeHTTPError() { - self::$called_error = true; + ControllerExtension::$called_error = true; } /** @@ -35,6 +35,6 @@ public function onBeforeHTTPError() */ public function onBeforeHTTPError404() { - self::$called_404_error = true; + ControllerExtension::$called_404_error = true; } } diff --git a/tests/php/Dev/DevAdminControllerTest/Controller1.php b/tests/php/Dev/DevAdminControllerTest/Controller1.php index e2db8f78fc4..e73ee27ccfd 100644 --- a/tests/php/Dev/DevAdminControllerTest/Controller1.php +++ b/tests/php/Dev/DevAdminControllerTest/Controller1.php @@ -22,11 +22,11 @@ class Controller1 extends Controller public function index() { - echo self::OK_MSG; + echo Controller1::OK_MSG; } public function y1Action() { - echo self::OK_MSG; + echo Controller1::OK_MSG; } } diff --git a/tests/php/Dev/DevAdminControllerTest/ControllerWithPermissions.php b/tests/php/Dev/DevAdminControllerTest/ControllerWithPermissions.php index 7cbd2d276ce..3dcda947108 100644 --- a/tests/php/Dev/DevAdminControllerTest/ControllerWithPermissions.php +++ b/tests/php/Dev/DevAdminControllerTest/ControllerWithPermissions.php @@ -22,7 +22,7 @@ class ControllerWithPermissions extends Controller implements PermissionProvider public function index() { - echo self::OK_MSG; + echo ControllerWithPermissions::OK_MSG; } public function canInit() diff --git a/tests/php/Dev/SapphireTestTest/DataProvider.php b/tests/php/Dev/SapphireTestTest/DataProvider.php index 922a46c48dc..bb33b86b48a 100644 --- a/tests/php/Dev/SapphireTestTest/DataProvider.php +++ b/tests/php/Dev/SapphireTestTest/DataProvider.php @@ -32,7 +32,7 @@ public static function provideEqualListsWithEmptyList() [], ], ], - self::provideEqualLists() + DataProvider::provideEqualLists() ); } @@ -46,34 +46,34 @@ public static function provideEqualLists() [ ['FirstName' => 'Ingo'], ], - self::$oneItemList, + DataProvider::$oneItemList, ], 'twoParametersOneItem' => [ [ ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], ], - self::$oneItemList, + DataProvider::$oneItemList, ], 'oneParameterTwoItems' => [ [ ['FirstName' => 'Ingo'], ['FirstName' => 'Sam'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'twoParametersTwoItems' => [ [ ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], ['FirstName' => 'Sam', 'Surname' => 'Minnee'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'mixedParametersTwoItems' => [ [ ['FirstName' => 'Ingo', 'Surname' => 'Schommer'], ['FirstName' => 'Sam'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], ]; } @@ -95,28 +95,28 @@ public static function provideNonEqualLists() [ ['FirstName' => 'Ingo'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'oneExpectationHasWrontParamter' => [ [ ['FirstName' => 'IngoXX'], ['FirstName' => 'Sam'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'differentParametersInDifferentItemsAreWrong' => [ [ ['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'], ['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'differentParametersNotMatching' => [ [ ['FirstName' => 'Daniel', 'Surname' => 'Foo'], ['FirstName' => 'Dan'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], ]; } @@ -137,21 +137,21 @@ public static function provideNotContainingList() [ ['FirstName' => 'Sam'], ], - self::$oneItemList, + DataProvider::$oneItemList, ], 'twoParametersAreWrong' => [ [ ['FirstName' => 'IngoXXX', 'Surname' => 'Schommer'], ['FirstName' => 'Sam', 'Surname' => 'MinneeXXX'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], 'mixedList' => [ [ ['FirstName' => 'Daniel', 'Surname' => 'Foo'], ['FirstName' => 'Dan'], ], - self::$twoItemList, + DataProvider::$twoItemList, ], ]; } @@ -164,12 +164,12 @@ public static function provideAllMatchingList() return [ 'emptyMatch' => [ [], - self::$memberList, + DataProvider::$memberList, 'empty list did not match', ], 'allItemsWithLocaleSet' => [ ['Locale' => 'en_US'], - self::$memberList, + DataProvider::$memberList, 'list with Locale set in all items did not match', ], ]; @@ -181,7 +181,7 @@ public static function provideAllMatchingList() public static function provideNotMatchingList() { return [ - 'notAllItemsHaveLocaleSet' => [['FirstName' => 'Ingo'], self::$memberList], + 'notAllItemsHaveLocaleSet' => [['FirstName' => 'Ingo'], DataProvider::$memberList], ]; } } diff --git a/tests/php/Logging/DetailedErrorFormatterTest.php b/tests/php/Logging/DetailedErrorFormatterTest.php index fb36b91d190..1aa90eac2df 100644 --- a/tests/php/Logging/DetailedErrorFormatterTest.php +++ b/tests/php/Logging/DetailedErrorFormatterTest.php @@ -43,7 +43,7 @@ public function testFormatWithoutException() $this->assertStringContainsString('ERRNO 401', $result, 'Status code was not found in trace'); $this->assertStringContainsString('Denied', $result, 'Message was not found in trace'); $this->assertStringContainsString('Line 4 in index.php', $result, 'Line or filename were not found in trace'); - $this->assertStringContainsString(self::class, $result, 'Backtrace doesn\'t show current test class'); + $this->assertStringContainsString(DetailedErrorFormatterTest::class, $result, 'Backtrace doesn\'t show current test class'); } public function testFormatBatch() diff --git a/tests/php/ORM/DataListEagerLoadingTest.php b/tests/php/ORM/DataListEagerLoadingTest.php index 65950a9ae89..13c2460c8f8 100644 --- a/tests/php/ORM/DataListEagerLoadingTest.php +++ b/tests/php/ORM/DataListEagerLoadingTest.php @@ -46,7 +46,7 @@ class DataListEagerLoadingTest extends SapphireTest private const SHOW_QUERIES_RESET = 'SET_TO_THIS_VALUE_WHEN_FINISHED'; - private $showQueries = self::SHOW_QUERIES_RESET; + private $showQueries = DataListEagerLoadingTest::SHOW_QUERIES_RESET; public static function getExtraDataObjects() { @@ -122,7 +122,7 @@ public static function setUpBeforeClass(): void */ private function startCountingSelectQueries(): void { - if ($this->showQueries !== self::SHOW_QUERIES_RESET) { + if ($this->showQueries !== DataListEagerLoadingTest::SHOW_QUERIES_RESET) { throw new LogicException('showQueries wasnt reset, you did something wrong'); } $this->showQueries = $_REQUEST['showqueries'] ?? null; @@ -151,7 +151,7 @@ private function stopCountingSelectQueries(): int */ private function resetShowQueries(): void { - if ($this->showQueries === self::SHOW_QUERIES_RESET) { + if ($this->showQueries === DataListEagerLoadingTest::SHOW_QUERIES_RESET) { return; } if ($this->showQueries) { @@ -159,7 +159,7 @@ private function resetShowQueries(): void } else { unset($_REQUEST['showqueries']); } - $this->showQueries = self::SHOW_QUERIES_RESET; + $this->showQueries = DataListEagerLoadingTest::SHOW_QUERIES_RESET; } /** diff --git a/tests/php/ORM/DataObjectTest/MockDynamicAssignmentDataObject.php b/tests/php/ORM/DataObjectTest/MockDynamicAssignmentDataObject.php index fc863f512cc..fc8ed726a27 100644 --- a/tests/php/ORM/DataObjectTest/MockDynamicAssignmentDataObject.php +++ b/tests/php/ORM/DataObjectTest/MockDynamicAssignmentDataObject.php @@ -30,11 +30,11 @@ class MockDynamicAssignmentDataObject extends DataObject implements TestOnly ]; private static $many_many = [ - 'MockManyMany' => self::class, + 'MockManyMany' => MockDynamicAssignmentDataObject::class, ]; private static $belongs_many_many = [ - 'MockBelongsManyMany' => self::class, + 'MockBelongsManyMany' => MockDynamicAssignmentDataObject::class, ]; private static $many_many_extraFields = [ diff --git a/tests/php/ORM/DataObjectTest/TreeNode.php b/tests/php/ORM/DataObjectTest/TreeNode.php index e497748b29a..43a6535c7d8 100644 --- a/tests/php/ORM/DataObjectTest/TreeNode.php +++ b/tests/php/ORM/DataObjectTest/TreeNode.php @@ -25,12 +25,12 @@ class TreeNode extends DataObject implements TestOnly ]; private static $has_one = [ - 'Parent' => self::class, - 'Cycle' => self::class, + 'Parent' => TreeNode::class, + 'Cycle' => TreeNode::class, ]; private static $has_many = [ - 'Children' => self::class, + 'Children' => TreeNode::class, ]; public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) @@ -51,7 +51,7 @@ public function write($showDebug = false, $forceInsert = false, $forceWrite = fa public function resetCounts() { $update = new SQLUpdate( - sprintf('"%s"', self::baseTable()), + sprintf('"%s"', TreeNode::baseTable()), ['"WriteCount"' => 0] ); $results = $update->execute(); diff --git a/tests/php/ORM/Filters/EndsWithFilterTest.php b/tests/php/ORM/Filters/EndsWithFilterTest.php index ea5d51d4d2f..d8825d26c4c 100644 --- a/tests/php/ORM/Filters/EndsWithFilterTest.php +++ b/tests/php/ORM/Filters/EndsWithFilterTest.php @@ -5,6 +5,7 @@ use SilverStripe\Dev\SapphireTest; use SilverStripe\ORM\Filters\EndsWithFilter; use SilverStripe\View\ArrayData; +use SilverStripe\ORM\Filters\SearchFilter; class EndsWithFilterTest extends SapphireTest { @@ -267,7 +268,7 @@ public function testMatches(mixed $filterValue, mixed $matchValue, array $modifi } } - EndsWithFilter::config()->set('default_case_sensitive', $caseSensitive); + SearchFilter::config()->set('default_case_sensitive', $caseSensitive); $filter = new EndsWithFilter(); $filter->setValue($filterValue); $filter->setModifiers($modifiers); diff --git a/tests/php/ORM/Filters/ExactMatchFilterTest.php b/tests/php/ORM/Filters/ExactMatchFilterTest.php index aa66b2641ad..61cf04d42df 100644 --- a/tests/php/ORM/Filters/ExactMatchFilterTest.php +++ b/tests/php/ORM/Filters/ExactMatchFilterTest.php @@ -9,6 +9,7 @@ use SilverStripe\ORM\Tests\Filters\ExactMatchFilterTest\Project; use SilverStripe\ORM\DataList; use SilverStripe\View\ArrayData; +use SilverStripe\ORM\Filters\SearchFilter; class ExactMatchFilterTest extends SapphireTest { @@ -313,7 +314,7 @@ public function testMatches(mixed $filterValue, mixed $objValue, array $modifier } } - ExactMatchFilter::config()->set('default_case_sensitive', $caseSensitive); + SearchFilter::config()->set('default_case_sensitive', $caseSensitive); $filter = new ExactMatchFilter(); $filter->setValue($filterValue); $filter->setModifiers($modifiers); diff --git a/tests/php/ORM/Filters/PartialMatchFilterTest.php b/tests/php/ORM/Filters/PartialMatchFilterTest.php index 8f39248b37e..f4ad899427d 100644 --- a/tests/php/ORM/Filters/PartialMatchFilterTest.php +++ b/tests/php/ORM/Filters/PartialMatchFilterTest.php @@ -5,6 +5,7 @@ use SilverStripe\Dev\SapphireTest; use SilverStripe\ORM\Filters\PartialMatchFilter; use SilverStripe\View\ArrayData; +use SilverStripe\ORM\Filters\SearchFilter; class PartialMatchFilterTest extends SapphireTest { @@ -267,7 +268,7 @@ public function testMatches(mixed $filterValue, mixed $objValue, array $modifier } } - PartialMatchFilter::config()->set('default_case_sensitive', $caseSensitive); + SearchFilter::config()->set('default_case_sensitive', $caseSensitive); $filter = new PartialMatchFilter(); $filter->setValue($filterValue); $filter->setModifiers($modifiers); diff --git a/tests/php/ORM/Filters/StartsWithFilterTest.php b/tests/php/ORM/Filters/StartsWithFilterTest.php index 5d4cac344c3..855020f53a6 100644 --- a/tests/php/ORM/Filters/StartsWithFilterTest.php +++ b/tests/php/ORM/Filters/StartsWithFilterTest.php @@ -5,6 +5,7 @@ use SilverStripe\Dev\SapphireTest; use SilverStripe\ORM\Filters\StartsWithFilter; use SilverStripe\View\ArrayData; +use SilverStripe\ORM\Filters\SearchFilter; class StartsWithFilterTest extends SapphireTest { @@ -267,7 +268,7 @@ public function testMatches(mixed $filterValue, mixed $matchValue, array $modifi } } - StartsWithFilter::config()->set('default_case_sensitive', $caseSensitive); + SearchFilter::config()->set('default_case_sensitive', $caseSensitive); $filter = new StartsWithFilter(); $filter->setValue($filterValue); $filter->setModifiers($modifiers); diff --git a/tests/php/ORM/MarkedSetTest.php b/tests/php/ORM/MarkedSetTest.php index 104efe472a1..e2af6cffd55 100644 --- a/tests/php/ORM/MarkedSetTest.php +++ b/tests/php/ORM/MarkedSetTest.php @@ -394,7 +394,7 @@ protected function assertTreeContains($html, $nodes, $message = null) $xpath .= '/ul/li[@data-id="' . $node->ID . '"]'; } $match = $parser->getByXpath($xpath); - self::assertThat((bool)$match, self::isTrue(), $message); + MarkedSetTest::assertThat((bool)$match, MarkedSetTest::isTrue(), $message); } /** @@ -410,7 +410,7 @@ protected function assertTreeNotContains($html, $nodes, $message = null) $xpath .= '/ul/li[@data-id="' . $node->ID . '"]'; } $match = $parser->getByXpath($xpath); - self::assertThat((bool)$match, self::isFalse(), $message); + MarkedSetTest::assertThat((bool)$match, MarkedSetTest::isFalse(), $message); } /** diff --git a/tests/php/ORM/MySQLiConnectorTest.php b/tests/php/ORM/MySQLiConnectorTest.php index 0a46b0e915b..8da8b65dd1b 100644 --- a/tests/php/ORM/MySQLiConnectorTest.php +++ b/tests/php/ORM/MySQLiConnectorTest.php @@ -62,7 +62,7 @@ public function testConnectionCharsetControl($charset, $defaultCollation) // Note: we do not need to update the utf charset here because mysqli with newer // version of mysql/mariadb still self-reports as 'utf8' rather than 'utf8mb3' - // This is unlike self::testConnectionCollationControl() + // This is unlike MySQLiConnectorTest::testConnectionCollationControl() $this->assertEquals($charset, $cset->charset); $this->assertEquals($defaultCollation, $cset->collation); diff --git a/tests/php/ORM/RelatedDataServiceTest.php b/tests/php/ORM/RelatedDataServiceTest.php index dd1988698c8..93efd4b5e6b 100644 --- a/tests/php/ORM/RelatedDataServiceTest.php +++ b/tests/php/ORM/RelatedDataServiceTest.php @@ -109,7 +109,7 @@ public function testUsageHasOneHubExtension() // Add DataExtension and reset database so that tables + columns get added Hub::add_extension(HubExtension::class); DataObject::reset(); - self::resetDBSchema(true, true); + RelatedDataServiceTest::resetDBSchema(true, true); // $pageTitle = 'My Page that has_one File using HubExtension'; $myFile = new Node(); @@ -215,7 +215,7 @@ public function testUsageManyManyWithoutBelongsHubExtension() // Add DataExtension and reset database so that tables + columns get added Hub::add_extension(HubExtension::class); DataObject::reset(); - self::resetDBSchema(true, true); + RelatedDataServiceTest::resetDBSchema(true, true); // $pageTitle = 'My Page that many_many File without belong_many_many Page using HubExtension'; $myPage = new Hub(); diff --git a/tests/php/ORM/SQLSelectTest/CteRecursiveObject.php b/tests/php/ORM/SQLSelectTest/CteRecursiveObject.php index 6423b2e12d1..93a15156951 100644 --- a/tests/php/ORM/SQLSelectTest/CteRecursiveObject.php +++ b/tests/php/ORM/SQLSelectTest/CteRecursiveObject.php @@ -14,10 +14,10 @@ class CteRecursiveObject extends DataObject implements TestOnly ]; private static $has_one = [ - 'Parent' => self::class, + 'Parent' => CteRecursiveObject::class, ]; private static $has_many = [ - 'Children' => self::class . '.Parent', + 'Children' => CteRecursiveObject::class . '.Parent', ]; } diff --git a/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php b/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php index 066ff9ca0fc..a3e59caf6ee 100644 --- a/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php +++ b/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php @@ -47,7 +47,7 @@ public function flushMemberCache($memberIDs = null) } if ($memberIDs && is_array($memberIDs)) { - foreach (self::$categories as $category) { + foreach (TestCacheFlusher::$categories as $category) { foreach ($memberIDs as $memberID) { $key = $this->generateCacheKey($category, $memberID); $this->cache->delete($key); diff --git a/tests/php/Security/InheritedPermissionsTest/TestPermissionNode.php b/tests/php/Security/InheritedPermissionsTest/TestPermissionNode.php index f769a4802d9..1621f40ed85 100644 --- a/tests/php/Security/InheritedPermissionsTest/TestPermissionNode.php +++ b/tests/php/Security/InheritedPermissionsTest/TestPermissionNode.php @@ -23,7 +23,7 @@ class TestPermissionNode extends DataObject implements TestOnly ]; private static $has_one = [ - "Parent" => self::class, + "Parent" => TestPermissionNode::class, ]; private static $table_name = 'InheritedPermissionsTest_TestPermissionNode'; diff --git a/tests/php/Security/InheritedPermissionsTest/UnstagedNode.php b/tests/php/Security/InheritedPermissionsTest/UnstagedNode.php index db45f0831fa..ab816bbd17c 100644 --- a/tests/php/Security/InheritedPermissionsTest/UnstagedNode.php +++ b/tests/php/Security/InheritedPermissionsTest/UnstagedNode.php @@ -23,7 +23,7 @@ class UnstagedNode extends DataObject implements TestOnly ]; private static $has_one = [ - "Parent" => self::class, + "Parent" => UnstagedNode::class, ]; private static $table_name = 'InheritedPermissionsTest_UnstagedNode'; diff --git a/tests/php/View/RequirementsTest.php b/tests/php/View/RequirementsTest.php index c2582de9e14..30838d4eba9 100644 --- a/tests/php/View/RequirementsTest.php +++ b/tests/php/View/RequirementsTest.php @@ -62,7 +62,7 @@ public function testExternalUrls() $backend->css('//scheme-relative.example.com/test.css'); $backend->css('http://www.mydomain.com:3000/test.css'); - $html = $backend->includeInHTML(self::$html_template); + $html = $backend->includeInHTML(RequirementsTest::$html_template); $this->assertStringContainsString('http://www.mydomain.com/test.js', $html, 'Load external javascript URL'); $this->assertStringContainsString('https://www.mysecuredomain.com/test.js', $html, 'Load external secure javascript URL'); @@ -89,7 +89,7 @@ public function testResolveCSSReferencesDisabled() ] ); - $backend->includeInHTML(self::$html_template); + $backend->includeInHTML(RequirementsTest::$html_template); // we get the file path here $allCSS = $backend->getCSS(); @@ -137,7 +137,7 @@ public function testResolveCSSReferences() ] ); - $backend->includeInHTML(self::$html_template); + $backend->includeInHTML(RequirementsTest::$html_template); // we get the file path here $allCSS = $backend->getCSS(); @@ -389,7 +389,7 @@ public function testCustomType() [ 'type' => 'application/json' ] ); $backend->javascript('javascript/RequirementsTest_b.js'); - $result = $backend->includeInHTML(self::$html_template); + $result = $backend->includeInHTML(RequirementsTest::$html_template); $this->assertMatchesRegularExpression( '#