diff --git a/.github/workflows/add-prs-to-project.yml b/.github/workflows/add-prs-to-project.yml
new file mode 100644
index 000000000..2d3f41ada
--- /dev/null
+++ b/.github/workflows/add-prs-to-project.yml
@@ -0,0 +1,22 @@
+name: Add new PRs to github project
+
+on:
+ pull_request_target:
+ types:
+ - opened
+ - ready_for_review
+
+permissions: {}
+
+jobs:
+ addprtoproject:
+ name: Add PR to GitHub Project
+ # Only run on the silverstripe account
+ if: github.repository_owner == 'silverstripe'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Add PR to github project
+ uses: silverstripe/gha-add-pr-to-project@v1
+ with:
+ app_id: ${{ vars.PROJECT_PERMISSIONS_APP_ID }}
+ private_key: ${{ secrets.PROJECT_PERMISSIONS_APP_PRIVATE_KEY }}
diff --git a/src/Control/ContentNegotiator.php b/src/Control/ContentNegotiator.php
index 21ec89f3e..aeb3b9f54 100644
--- a/src/Control/ContentNegotiator.php
+++ b/src/Control/ContentNegotiator.php
@@ -116,7 +116,7 @@ class ContentNegotiator
*/
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 80d7047c0..5b94f0ad6 100644
--- a/src/Control/Controller.php
+++ b/src/Control/Controller.php
@@ -573,7 +573,7 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
{
// 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 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
*/
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 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
}
// Normlise trailing slash
- $shouldHaveTrailingSlash = self::config()->uninherited('add_trailing_slash');
+ $shouldHaveTrailingSlash = Controller::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 2995e844f..2bcafa606 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 @@ class Cookie
$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 @@ class Cookie
*/
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 @@ class Cookie
*/
public static function get_all($includeUnsent = true)
{
- return self::get_inst()->getAll($includeUnsent);
+ return Cookie::get_inst()->getAll($includeUnsent);
}
/**
@@ -104,7 +104,7 @@ class Cookie
*/
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 @@ class Cookie
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 f91fc93b4..8318e5dd6 100644
--- a/src/Control/Director.php
+++ b/src/Control/Director.php
@@ -238,7 +238,7 @@ class Director implements TemplateGlobalProvider
// 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 @@ class Director implements TemplateGlobalProvider
*/
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 @@ class Director implements TemplateGlobalProvider
*/
public static function set_current_page($page)
{
- self::$current_page = $page;
+ Director::$current_page = $page;
}
/**
@@ -394,7 +394,7 @@ class Director implements TemplateGlobalProvider
* - 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 eefc1b36d..9c7d4f5da 100644 --- a/src/Dev/Deprecation.php +++ b/src/Dev/Deprecation.php @@ -111,14 +111,14 @@ class Deprecation */ 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 @@ class Deprecation } $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 @@ class Deprecation */ public static function isTriggeringError(): bool { - return self::$isTriggeringError; + return Deprecation::$isTriggeringError; } /** @@ -195,7 +195,7 @@ class Deprecation */ public static function setShouldShowForHttp(bool $value): void { - self::$shouldShowForHttp = $value; + Deprecation::$shouldShowForHttp = $value; } /** @@ -206,7 +206,7 @@ class Deprecation */ public static function setShouldShowForCli(bool $value): void { - self::$shouldShowForCli = $value; + Deprecation::$shouldShowForCli = $value; } /** @@ -217,9 +217,9 @@ class Deprecation { 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 @@ class Deprecation { 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 @@ class Deprecation // 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 @@ class Deprecation // 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 @@ class Deprecation $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 @@ class Deprecation $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 0a77da807..4607e4472 100644 --- a/src/Dev/Install/DatabaseAdapterRegistry.php +++ b/src/Dev/Install/DatabaseAdapterRegistry.php @@ -96,10 +96,10 @@ class DatabaseAdapterRegistry implements Flushable // 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 @@ class DatabaseAdapterRegistry implements Flushable */ public static function unregister($class) { - unset(self::$adapters[$class]); + unset(DatabaseAdapterRegistry::$adapters[$class]); } /** @@ -204,7 +204,7 @@ class DatabaseAdapterRegistry implements Flushable */ public static function get_adapters() { - return self::$adapters; + return DatabaseAdapterRegistry::$adapters; } /** @@ -215,8 +215,8 @@ class DatabaseAdapterRegistry implements Flushable */ 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 @@ class DatabaseAdapterRegistry implements Flushable */ 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 df953acc2..b54a58e55 100644 --- a/src/Dev/SapphireTest.php +++ b/src/Dev/SapphireTest.php @@ -206,7 +206,7 @@ abstract class SapphireTest extends TestCase implements TestOnly */ protected static function is_running_test() { - return self::$is_running_test; + return SapphireTest::$is_running_test; } /** @@ -216,7 +216,7 @@ abstract class SapphireTest extends TestCase implements TestOnly */ protected static function set_is_running_test($bool) { - self::$is_running_test = $bool; + SapphireTest::$is_running_test = $bool; } /** @@ -661,7 +661,7 @@ abstract class SapphireTest extends TestCase implements TestOnly public static function assertListContains($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -699,7 +699,7 @@ abstract class SapphireTest extends TestCase implements TestOnly public static function assertListNotContains($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -739,7 +739,7 @@ abstract class SapphireTest extends TestCase implements TestOnly public static function assertListEquals($matches, SS_List $list, $message = '') { if (!is_array($matches)) { - throw self::createInvalidArgumentException( + throw SapphireTest::createInvalidArgumentException( 1, 'array' ); @@ -770,7 +770,7 @@ abstract class SapphireTest extends TestCase implements TestOnly 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 67229f5ca..2e501b150 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 @@ class TestKernel extends CoreKernel */ 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 0b85bbbbf..2b1b7e720 100644 --- a/src/Dev/Validation/RelationValidationService.php +++ b/src/Dev/Validation/RelationValidationService.php @@ -82,7 +82,7 @@ class RelationValidationService implements Resettable public static function reset(): void { - $service = self::singleton(); + $service = RelationValidationService::singleton(); $service->clearErrors(); $service->ignoreConfig = false; } @@ -98,7 +98,7 @@ class RelationValidationService implements Resettable */ public function validateRelations(): array { - self::reset(); + RelationValidationService::reset(); $classes = ClassInfo::subclassesFor(DataObject::class); return $this->validateClasses($classes); @@ -139,7 +139,7 @@ class RelationValidationService implements Resettable */ 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 bdabb9bea..fa61dc91a 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 111bbf120..69151c121 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 @@ class Form extends ViewableData implements HasRequestHandler // 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 @@ class Form extends ViewableData implements HasRequestHandler */ 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 @@ class Form extends ViewableData implements HasRequestHandler * in which case the default form behaviour will kick in. * * @param $callback - * @return self + * @return Form */ public function setValidationResponseCallback($callback) { @@ -954,12 +954,12 @@ class Form extends ViewableData implements HasRequestHandler 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 @@ class Form extends ViewableData implements HasRequestHandler // 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 @@ class Form extends ViewableData implements HasRequestHandler // 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 @@ class Form extends ViewableData implements HasRequestHandler // 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 7571418ba..b900fbcd2 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 c6a56ece7..77a46ef2c 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 @@ class FormField extends RequestHandler $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 @@ class FormField extends RequestHandler * @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 1707fafdb..d6039fe4c 100644 --- a/src/Forms/GridField/GridField.php +++ b/src/Forms/GridField/GridField.php @@ -567,11 +567,11 @@ class GridField extends FormField // 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) { @@ -587,7 +587,7 @@ class GridField extends FormField // 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 07299cc93..e776f333d 100644 --- a/src/Forms/GridField/GridFieldDetailForm.php +++ b/src/Forms/GridField/GridFieldDetailForm.php @@ -285,7 +285,7 @@ class GridFieldDetailForm extends AbstractGridFieldComponent implements GridFiel * 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 1fb47d249..2e96e28f8 100755 --- a/src/Forms/GridField/GridFieldFilterHeader.php +++ b/src/Forms/GridField/GridFieldFilterHeader.php @@ -92,7 +92,7 @@ class GridFieldFilterHeader extends AbstractGridFieldComponent implements GridFi 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 2bbc7d791..f74c60a23 100644 --- a/src/Forms/GridField/GridState_Data.php +++ b/src/Forms/GridField/GridState_Data.php @@ -25,14 +25,14 @@ class GridState_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 @@ class GridState_Data $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 824d11f73..6c685bf29 100644 --- a/src/Forms/HTMLEditor/HTMLEditorConfig.php +++ b/src/Forms/HTMLEditor/HTMLEditorConfig.php @@ -81,11 +81,11 @@ abstract class HTMLEditorConfig 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 @@ abstract class HTMLEditorConfig 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 @@ abstract class HTMLEditorConfig */ public static function set_active_identifier($identifier) { - self::$current = $identifier; + HTMLEditorConfig::$current = $identifier; } /** @@ -147,7 +147,7 @@ abstract class HTMLEditorConfig */ 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 @@ abstract class HTMLEditorConfig */ 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 @@ abstract class HTMLEditorConfig { $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 8b5076f39..eed09760a 100644 --- a/src/Forms/HTMLEditor/TinyMCEConfig.php +++ b/src/Forms/HTMLEditor/TinyMCEConfig.php @@ -740,7 +740,7 @@ class TinyMCEConfig extends HTMLEditorConfig implements i18nEntityProvider 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) { @@ -755,7 +755,7 @@ class TinyMCEConfig extends HTMLEditorConfig implements i18nEntityProvider ); } elseif (empty($preset['text']) && isset($preset['width'])) { $preset['text'] = _t( - self::class . '.PIXEL_WIDTH', + TinyMCEConfig::class . '.PIXEL_WIDTH', '{width} pixels', $preset ); @@ -945,7 +945,7 @@ class TinyMCEConfig extends HTMLEditorConfig implements i18nEntityProvider * @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; @@ -956,9 +956,9 @@ class TinyMCEConfig extends HTMLEditorConfig implements i18nEntityProvider 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 8a028726d..64bb339e3 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 610f6d82d..fa574c439 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 178cd1f09..d90b02a3c 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 b3a97be5e..1dcd6b502 100644 --- a/src/Forms/SingleSelectField.php +++ b/src/Forms/SingleSelectField.php @@ -67,7 +67,7 @@ abstract class SingleSelectField extends SelectField /** * @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 4247afa6b..49aa40b2c 100644 --- a/src/Forms/TextField.php +++ b/src/Forms/TextField.php @@ -78,7 +78,7 @@ class TextField extends FormField implements TippableFieldInterface * @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 79b625458..57e43aeb6 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 @@ class Tip * @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 @@ class Tip * @param string $icon * @return Tip */ - public function setIcon(string $icon): self + public function setIcon(string $icon): Tip { $this->icon = $icon; @@ -125,7 +125,7 @@ class Tip * @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 b2f9952c9..c503c591a 100644 --- a/src/Forms/TreeDropdownField.php +++ b/src/Forms/TreeDropdownField.php @@ -57,7 +57,7 @@ use SilverStripe\ORM\Hierarchy\MarkedSet; */ 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 @@ class TreeDropdownField extends FormField implements HasOneRelationFieldInterfac } 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 @@ class TreeDropdownField extends FormField implements HasOneRelationFieldInterfac 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 @@ class TreeDropdownField extends FormField implements HasOneRelationFieldInterfac /** * @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 5a03fabee..371d0f6df 100644 --- a/src/ORM/ArrayLib.php +++ b/src/ORM/ArrayLib.php @@ -82,7 +82,7 @@ class ArrayLib */ public static function array_values_recursive($array) { - return self::flatten($array, false); + return ArrayLib::flatten($array, false); } /** @@ -146,7 +146,7 @@ class ArrayLib 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 89bc4db79..f2f16d034 100644 --- a/src/ORM/Connect/DBQueryBuilder.php +++ b/src/ORM/Connect/DBQueryBuilder.php @@ -99,7 +99,7 @@ class DBQueryBuilder // 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 183aef2a7..6b7dc9c01 100644 --- a/src/ORM/Connect/Database.php +++ b/src/ORM/Connect/Database.php @@ -234,9 +234,9 @@ abstract class Database $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 @@ abstract class Database */ public static function setWhitelistQueryArray($whitelistArray) { - self::$whitelist_array = $whitelistArray; + Database::$whitelist_array = $whitelistArray; } /** @@ -287,7 +287,7 @@ abstract class Database */ 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 755304287..dfea806a2 100644 --- a/src/ORM/Connect/MySQLQueryBuilder.php +++ b/src/ORM/Connect/MySQLQueryBuilder.php @@ -47,7 +47,7 @@ class MySQLQueryBuilder extends DBQueryBuilder } 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 bcab13413..a4e3cafa8 100644 --- a/src/ORM/Connect/MySQLSchemaManager.php +++ b/src/ORM/Connect/MySQLSchemaManager.php @@ -23,8 +23,8 @@ class MySQLSchemaManager extends DBSchemaManager { $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 @@ class MySQLSchemaManager extends DBSchemaManager } } - $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 @@ class MySQLSchemaManager extends DBSchemaManager // 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 @@ class MySQLSchemaManager extends DBSchemaManager 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 ca6cad20c..2fbbd70c5 100644 --- a/src/ORM/Connect/MySQLiConnector.php +++ b/src/ORM/Connect/MySQLiConnector.php @@ -108,7 +108,7 @@ class MySQLiConnector extends DBConnector 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 70e5d1277..214998c37 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 @@ class NullDatabase extends Database /** * @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 7be15a65c..054b858d0 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 @@ class DB */ 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 @@ class DB */ 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 @@ class DB */ 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 @@ class DB */ 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 @@ class DB 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 @@ class DB } $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 @@ class DB 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 @@ class DB 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 @@ class DB 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 @@ class DB */ public static function connection_attempted() { - return self::$connection_attempted; + return DB::$connection_attempted; } /** @@ -334,9 +334,9 @@ class DB */ 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 @@ class DB */ 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 @@ class DB */ 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 @@ class DB */ public static function get_generated_id($table) { - return self::get_conn()->getGeneratedID($table); + return DB::get_conn()->getGeneratedID($table); } /** @@ -495,7 +495,7 @@ class DB */ public static function is_active() { - return ($conn = self::get_conn()) && $conn->isActive(); + return ($conn = DB::get_conn()) && $conn->isActive(); } /** @@ -508,7 +508,7 @@ class DB */ public static function create_database($database) { - return self::get_conn()->selectDatabase($database, true); + return DB::get_conn()->selectDatabase($database, true); } /** @@ -531,7 +531,7 @@ class DB $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 @@ class DB */ 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 @@ class DB $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 @@ class DB */ 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 @@ class DB */ 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 @@ class DB */ public static function dont_require_table($table) { - self::get_schema()->dontRequireTable($table); + DB::get_schema()->dontRequireTable($table); } /** @@ -613,7 +613,7 @@ class DB */ public static function dont_require_field($table, $fieldName) { - self::get_schema()->dontRequireField($table, $fieldName); + DB::get_schema()->dontRequireField($table, $fieldName); } /** @@ -624,7 +624,7 @@ class DB */ public static function check_and_repair_table($table) { - return self::get_schema()->checkAndRepairTable($table); + return DB::get_schema()->checkAndRepairTable($table); } /** @@ -634,7 +634,7 @@ class DB */ public static function affected_rows() { - return self::get_conn()->affectedRows(); + return DB::get_conn()->affectedRows(); } /** @@ -645,7 +645,7 @@ class DB */ public static function table_list() { - return self::get_schema()->tableList(); + return DB::get_schema()->tableList(); } /** @@ -657,7 +657,7 @@ class DB */ public static function field_list($table) { - return self::get_schema()->fieldList($table); + return DB::get_schema()->fieldList($table); } /** @@ -667,7 +667,7 @@ class DB */ public static function quiet($quiet = true) { - self::get_schema()->quiet($quiet); + DB::get_schema()->quiet($quiet); } /** @@ -678,6 +678,6 @@ class DB */ 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 5cada9781..a576d96b6 100644 --- a/src/ORM/DataObject.php +++ b/src/ORM/DataObject.php @@ -343,10 +343,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; } /** @@ -358,7 +358,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity * 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(); @@ -372,7 +372,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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 @@ -383,13 +383,13 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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; } @@ -429,7 +429,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } break; - case self::CREATE_SINGLETON: + case DataObject::CREATE_SINGLETON: // No setting happens for a singleton $this->record['ID'] = 0; $this->record['ClassName'] = static::class; @@ -722,7 +722,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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; } @@ -750,14 +750,14 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity */ 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) { @@ -777,7 +777,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity { parent::defineMethods(); - if (static::class === self::class) { + if (static::class === DataObject::class) { return; } @@ -1299,7 +1299,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } /** - * 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. * @@ -1335,7 +1335,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } } } - if ($class == self::class) { + if ($class == DataObject::class) { break; } } @@ -1496,7 +1496,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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); } @@ -1823,7 +1823,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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; @@ -1906,7 +1906,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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)) { @@ -2085,7 +2085,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity )); } // 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)) { @@ -2448,7 +2448,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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; @@ -2810,7 +2810,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity * @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 = []; @@ -2821,15 +2821,15 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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 { @@ -2846,7 +2846,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } // 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) { @@ -2877,7 +2877,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity * @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); @@ -2965,13 +2965,13 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity // 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])) { @@ -3366,7 +3366,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity * @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. @@ -3384,14 +3384,14 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity // 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) { @@ -3446,7 +3446,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } // Validate class - if ($callerClass === self::class) { + if ($callerClass === DataObject::class) { throw new InvalidArgumentException('DataObject::get_one() cannot query non-subclass DataObject directly'); } @@ -3457,7 +3457,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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); @@ -3468,15 +3468,15 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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; @@ -3492,15 +3492,15 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity */ 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]); } } @@ -3516,8 +3516,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity */ 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) { @@ -3527,7 +3527,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } } } - self::$_cache_get_one = []; + DataObject::$_cache_get_one = []; } /** @@ -3538,8 +3538,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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 = []; } /** @@ -3567,7 +3567,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } // Validate class - if ($class === self::class) { + if ($class === DataObject::class) { throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly'); } @@ -3670,7 +3670,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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( @@ -3679,7 +3679,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity } if ($fields) { - $hasAutoIncPK = get_parent_class($this ?? '') === self::class; + $hasAutoIncPK = get_parent_class($this ?? '') === DataObject::class; DB::require_table( $table, $fields, @@ -3911,7 +3911,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity * 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() @@ -3924,7 +3924,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity { $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 = []; @@ -3970,10 +3970,10 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $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]; } /** @@ -4092,7 +4092,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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; } /** @@ -4101,7 +4101,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity 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 6b0acfbce..9fc2ca664 100644 --- a/src/ORM/DataObjectSchema.php +++ b/src/ORM/DataObjectSchema.php @@ -206,9 +206,9 @@ class DataObjectSchema 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 @@ class DataObjectSchema } // 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 @@ class DataObjectSchema } $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 @@ class DataObjectSchema 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 @@ class DataObjectSchema } $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 @@ class DataObjectSchema ); } - 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 ef8f6b67b..c92309869 100644 --- a/src/ORM/DataQuery.php +++ b/src/ORM/DataQuery.php @@ -743,7 +743,7 @@ class DataQuery $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 8bec6c948..8a53c8890 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 @@ class EagerLoadedList extends ViewableData implements Relation, SS_List, Filtera * * @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 @@ class EagerLoadedList extends ViewableData implements Relation, SS_List, Filtera 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 b19633d87..a035d0188 100644 --- a/src/ORM/FieldType/DBDate.php +++ b/src/ORM/FieldType/DBDate.php @@ -45,7 +45,7 @@ class DBDate extends DBField $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 @@ class DBDate extends DBField */ public function getISOFormat() { - return self::ISO_DATE; + return DBDate::ISO_DATE; } /** @@ -543,7 +543,7 @@ class DBDate extends DBField */ 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 @@ class DBDate extends DBField * @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 @@ class DBDate extends DBField */ 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 @@ class DBDate extends DBField // 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 @@ class DBDate extends DBField $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 @@ class DBDate extends DBField } 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 ca3c49e7a..877c707f2 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 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider */ 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 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider */ 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 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider throw new InvalidArgumentException('DBDatetime::set_mock_now(): Wrong format: ' . $value); } } - self::$mock_now = $datetime; + DBDatetime::$mock_now = $datetime; } /** @@ -242,7 +242,7 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider */ public static function clear_mock_now() { - self::$mock_now = null; + DBDatetime::$mock_now = null; } /** @@ -255,14 +255,14 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider */ 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 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider */ 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 31df29c46..b85dec013 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 @@ class DBEnum extends DBString } // 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 @@ class DBEnum extends DBString } // 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 079df6b8f..94b5ee31f 100644 --- a/src/ORM/FieldType/DBField.php +++ b/src/ORM/FieldType/DBField.php @@ -540,7 +540,7 @@ abstract class DBField extends ViewableData implements DBIndexable "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/DBString.php b/src/ORM/FieldType/DBString.php index 5427aafd9..875936d56 100644 --- a/src/ORM/FieldType/DBString.php +++ b/src/ORM/FieldType/DBString.php @@ -237,6 +237,6 @@ abstract class DBString extends DBField */ 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 54c680aef..6b1813eea 100644 --- a/src/ORM/FieldType/DBTime.php +++ b/src/ORM/FieldType/DBTime.php @@ -174,7 +174,7 @@ class DBTime extends DBField */ 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 daf06f987..f622252fb 100644 --- a/src/ORM/Filters/SearchFilter.php +++ b/src/ORM/Filters/SearchFilter.php @@ -474,7 +474,7 @@ abstract class SearchFilter } elseif (in_array('nocase', $modifiers ?? [])) { return false; } else { - $sensitive = self::config()->get('default_case_sensitive'); + $sensitive = SearchFilter::config()->get('default_case_sensitive'); if ($sensitive !== null) { return $sensitive; } @@ -488,13 +488,13 @@ abstract class SearchFilter */ 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 41d5411fe..40adbb8bf 100644 --- a/src/ORM/Hierarchy/Hierarchy.php +++ b/src/ORM/Hierarchy/Hierarchy.php @@ -298,9 +298,9 @@ class Hierarchy extends DataExtension // 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 @@ class Hierarchy extends DataExtension // 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 @@ class Hierarchy extends DataExtension 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 @@ class Hierarchy extends DataExtension $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 @@ class Hierarchy extends DataExtension { $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 @@ class Hierarchy extends DataExtension 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 18dc593fa..464480c16 100644 --- a/src/ORM/Hierarchy/MarkedSet.php +++ b/src/ORM/Hierarchy/MarkedSet.php @@ -275,7 +275,7 @@ class MarkedSet 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 c7a465a03..b063acb74 100644 --- a/src/ORM/ListDecorator.php +++ b/src/ORM/ListDecorator.php @@ -54,7 +54,7 @@ abstract class ListDecorator extends ViewableData implements SS_List, Sortable, * @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 52a7c0ef2..20c16c61a 100644 --- a/src/ORM/Queries/SQLConditionalExpression.php +++ b/src/ORM/Queries/SQLConditionalExpression.php @@ -241,7 +241,7 @@ abstract class SQLConditionalExpression extends SQLExpression 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 @@ abstract class SQLConditionalExpression extends SQLExpression // 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 9ea159184..ed0fc4cd1 100644 --- a/src/ORM/Queries/SQLSelect.php +++ b/src/ORM/Queries/SQLSelect.php @@ -560,7 +560,7 @@ class SQLSelect extends SQLConditionalExpression */ 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 1eeff1fd6..a4731e593 100644 --- a/src/ORM/Search/FulltextSearchable.php +++ b/src/ORM/Search/FulltextSearchable.php @@ -77,7 +77,7 @@ class FulltextSearchable extends DataExtension ); } } - 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 @@ class FulltextSearchable extends DataExtension */ 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 7cd782331..0c6834353 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 6d45996d5..8ba3ba545 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 @@ class ValidationResult 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 @@ class ValidationResult * 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 @@ class ValidationResult 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 9c47c1f1d..d99d7802d 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 @@ class BasicAuth * 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 @@ class BasicAuth // 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 ef4e01720..01f822398 100644 --- a/src/Security/Confirmation/Storage.php +++ b/src/Security/Confirmation/Storage.php @@ -368,7 +368,7 @@ class Storage } /** - * 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 @@ class Storage } /** - * 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 bcaa1f6b6..65b660448 100644 --- a/src/Security/InheritedPermissions.php +++ b/src/Security/InheritedPermissions.php @@ -147,7 +147,7 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher } 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher // 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher . " 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher } 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher // 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher public function canEditMultiple($ids, Member $member = null, $useCached = true) { return $this->batchPermissionCheck( - self::EDIT, + InheritedPermissions::EDIT, $ids, $member, $this->getGlobalEditPermissions(), @@ -472,7 +472,7 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher */ 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher { // 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher { // 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher { // 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher 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 @@ class InheritedPermissions implements PermissionChecker, MemberCacheFlusher 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 e8851c51e..03ad3a059 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 446ca6588..2003e8f05 100644 --- a/src/Security/Member.php +++ b/src/Security/Member.php @@ -478,7 +478,7 @@ class Member extends DataObject 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 @@ class Member extends DataObject 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 @@ class Member extends DataObject 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 @@ class Member extends DataObject */ 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 @@ class Member extends DataObject */ 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 @@ class Member extends DataObject 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 94dd5027d..eba6afc74 100644 --- a/src/Security/MemberAuthenticator/MemberLoginForm.php +++ b/src/Security/MemberAuthenticator/MemberLoginForm.php @@ -111,7 +111,7 @@ class MemberLoginForm extends BaseLoginForm 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 @@ class MemberLoginForm extends BaseLoginForm */ 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 56e42af7f..cbf648487 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 @@ abstract class PasswordEncryptor */ 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 877fdd124..0b6277d8f 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 @@ class PasswordEncryptor_Blowfish extends PasswordEncryptor */ public static function get_cost() { - return self::$cost; + return PasswordEncryptor_Blowfish::$cost; } public function encrypt($password, $salt = null, $member = null) @@ -153,7 +153,7 @@ class PasswordEncryptor_Blowfish extends PasswordEncryptor } /** - * 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 @@ class PasswordEncryptor_Blowfish extends PasswordEncryptor 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 c15757f57..ce57f81bb 100644 --- a/src/Security/Permission.php +++ b/src/Security/Permission.php @@ -122,7 +122,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl $member = Security::getCurrentUser(); } - return self::checkMember($member, $code, $arg, $strict); + return Permission::checkMember($member, $code, $arg, $strict); } /** @@ -136,7 +136,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl */ public static function reset() { - self::$cache_permissions = []; + Permission::$cache_permissions = []; } /** @@ -173,12 +173,12 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl 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 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl } // 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 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl // 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 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl array_merge( $codeParams, $adminParams, - [self::GRANT_PERMISSION], + [Permission::GRANT_PERMISSION], $groupParams, $argParams ) @@ -264,7 +264,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl \"Code\" IN ($codeClause) AND \"Type\" = ? )", - array_merge($codeParams, [self::GRANT_PERMISSION]) + array_merge($codeParams, [Permission::GRANT_PERMISSION]) )->value(); if (!$hasPermission) { @@ -283,7 +283,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl */ public static function permissions_for_member($memberID) { - $groupList = self::groupList($memberID); + $groupList = Permission::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); @@ -291,7 +291,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl $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 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl $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 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl $perm->Code = $code; } - $perm->Type = self::GRANT_PERMISSION; + $perm->Type = Permission::GRANT_PERMISSION; // Arg component switch ($arg) { @@ -426,7 +426,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl $perm->Code = $code; } - $perm->Type = self::DENY_PERMISSION; + $perm->Type = Permission::DENY_PERMISSION; // Arg component switch ($arg) { @@ -456,7 +456,7 @@ class Permission extends DataObject implements TemplateGlobalProvider, Resettabl */ 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 27f9f345b..389afcebd 100644 --- a/src/Security/RememberLoginHash.php +++ b/src/Security/RememberLoginHash.php @@ -217,9 +217,9 @@ class RememberLoginHash extends DataObject } 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 eea203ba4..214dbcb47 100644 --- a/src/Security/Security.php +++ b/src/Security/Security.php @@ -306,7 +306,7 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 @@ class Security extends Controller implements TemplateGlobalProvider */ public static function setCurrentUser($currentUser = null) { - self::$currentUser = $currentUser; + Security::$currentUser = $currentUser; } /** @@ -445,7 +445,7 @@ class Security extends Controller implements TemplateGlobalProvider */ public static function getCurrentUser() { - return self::$currentUser; + return Security::$currentUser; } /** @@ -1049,7 +1049,7 @@ class Security extends Controller implements TemplateGlobalProvider { // 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 @@ class Security extends Controller implements TemplateGlobalProvider 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 @@ class Security extends Controller implements TemplateGlobalProvider return false; } } - self::$database_is_ready = true; + Security::$database_is_ready = true; return true; } @@ -1125,8 +1125,8 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 @@ class Security extends Controller implements TemplateGlobalProvider */ public static function force_database_is_ready($isReady) { - self::$force_database_is_ready = $isReady; + Security::$force_database_is_ready = $isReady; } /** @@ -1165,12 +1165,12 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 @@ class Security extends Controller implements TemplateGlobalProvider */ 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 e6ba9c2f0..7c7ce6b90 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 @@ class SecurityToken implements TemplateGlobalProvider */ 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 @@ class SecurityToken implements TemplateGlobalProvider */ public static function disable() { - self::$enabled = false; - self::$inst = new NullSecurityToken(); + SecurityToken::$enabled = false; + SecurityToken::$inst = new NullSecurityToken(); } /** @@ -98,8 +98,8 @@ class SecurityToken implements TemplateGlobalProvider */ public static function enable() { - self::$enabled = true; - self::$inst = new SecurityToken(); + SecurityToken::$enabled = true; + SecurityToken::$inst = new SecurityToken(); } /** @@ -107,7 +107,7 @@ class SecurityToken implements TemplateGlobalProvider */ public static function is_enabled() { - return self::$enabled; + return SecurityToken::$enabled; } /** @@ -115,7 +115,7 @@ class SecurityToken implements TemplateGlobalProvider */ 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 33deb10bf..74fa8547f 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 @@ class SudoModeService implements SudoModeServiceInterface 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 5ede0200f..b7836cb4a 100644 --- a/src/View/Embed/EmbedContainer.php +++ b/src/View/Embed/EmbedContainer.php @@ -119,7 +119,7 @@ class EmbedContainer implements Embeddable 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 2ee11e6b1..17ea17639 100644 --- a/src/View/Parsers/HtmlDiff.php +++ b/src/View/Parsers/HtmlDiff.php @@ -31,21 +31,21 @@ class HtmlDiff { // 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 @@ class HtmlDiff } } - return self::cleanHTML($content); + return HtmlDiff::cleanHTML($content); } /** @@ -94,7 +94,7 @@ class HtmlDiff 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 @@ class HtmlDiff */ 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 @@ class HtmlDiff 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 @@ class HtmlDiff $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 @@ class HtmlDiff * 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 @@ class HtmlDiff 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 fefc024a4..4a73556a2 100644 --- a/src/View/Parsers/SQLFormatter.php +++ b/src/View/Parsers/SQLFormatter.php @@ -58,7 +58,7 @@ class SQLFormatter 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 1032c862a..2031a1645 100644 --- a/src/View/Parsers/ShortcodeParser.php +++ b/src/View/Parsers/ShortcodeParser.php @@ -58,11 +58,11 @@ class ShortcodeParser */ 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 @@ class ShortcodeParser */ public static function get_active() { - return static::get(self::$active_instance); + return static::get(ShortcodeParser::$active_instance); } /** @@ -82,7 +82,7 @@ class ShortcodeParser */ public static function set_active($identifier) { - self::$active_instance = (string) $identifier; + ShortcodeParser::$active_instance = (string) $identifier; } // -------------------------------------------------------------------------------------------------------------- @@ -192,7 +192,7 @@ class ShortcodeParser 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 @@ class ShortcodeParser protected static function attrrx() { - return '/' . self::$attrrx . '/xS'; + return '/' . ShortcodeParser::$attrrx . '/xS'; } protected static $tagrx = ' @@ -296,7 +296,7 @@ class ShortcodeParser 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 @@ class ShortcodeParser const LEAVE = 'leave'; const ERROR = 'error'; - public static $error_behavior = self::LEAVE; + public static $error_behavior = ShortcodeParser::LEAVE; /** @@ -380,7 +380,7 @@ class ShortcodeParser } if ($err) { - if (self::$error_behavior == self::ERROR) { + if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { throw new \Exception($err); } } else { @@ -407,9 +407,9 @@ class ShortcodeParser } // 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 @@ class ShortcodeParser $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 @@ class ShortcodeParser 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 @@ class ShortcodeParser 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 @@ class ShortcodeParser } $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 @@ class ShortcodeParser // 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 @@ class ShortcodeParser $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 @@ class ShortcodeParser $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 @@ class ShortcodeParser $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 c757f2ba2..0656d26dd 100644 --- a/src/View/Requirements.php +++ b/src/View/Requirements.php @@ -31,7 +31,7 @@ class Requirements implements Flushable { $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 @@ class Requirements implements Flushable */ public static function set_combined_files_enabled($enable) { - self::backend()->setCombinedFilesEnabled($enable); + Requirements::backend()->setCombinedFilesEnabled($enable); } /** @@ -52,7 +52,7 @@ class Requirements implements Flushable */ public static function get_combined_files_enabled() { - return self::backend()->getCombinedFilesEnabled(); + return Requirements::backend()->getCombinedFilesEnabled(); } /** @@ -62,7 +62,7 @@ class Requirements implements Flushable */ public static function set_combined_files_folder($folder) { - self::backend()->setCombinedFilesFolder($folder); + Requirements::backend()->setCombinedFilesFolder($folder); } /** @@ -75,7 +75,7 @@ class Requirements implements Flushable */ public static function set_suffix_requirements($var) { - self::backend()->setSuffixRequirements($var); + Requirements::backend()->setSuffixRequirements($var); } /** @@ -85,7 +85,7 @@ class Requirements implements Flushable */ public static function get_suffix_requirements() { - return self::backend()->getSuffixRequirements(); + return Requirements::backend()->getSuffixRequirements(); } /** @@ -101,10 +101,10 @@ class Requirements implements Flushable */ 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 @@ class Requirements implements Flushable */ public static function set_backend(Requirements_Backend $backend) { - self::$backend = $backend; + Requirements::$backend = $backend; } /** @@ -128,7 +128,7 @@ class Requirements implements Flushable */ public static function javascript($file, $options = []) { - self::backend()->javascript($file, $options); + Requirements::backend()->javascript($file, $options); } /** @@ -139,7 +139,7 @@ class Requirements implements Flushable */ public static function customScript($script, $uniquenessID = null) { - self::backend()->customScript($script, $uniquenessID); + Requirements::backend()->customScript($script, $uniquenessID); } /** @@ -154,7 +154,7 @@ class Requirements implements Flushable */ 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 @@ class Requirements implements Flushable */ public static function get_custom_scripts() { - return self::backend()->getCustomScripts(); + return Requirements::backend()->getCustomScripts(); } /** @@ -175,7 +175,7 @@ class Requirements implements Flushable */ public static function customCSS($script, $uniquenessID = null) { - self::backend()->customCSS($script, $uniquenessID); + Requirements::backend()->customCSS($script, $uniquenessID); } /** @@ -186,7 +186,7 @@ class Requirements implements Flushable */ public static function insertHeadTags($html, $uniquenessID = null) { - self::backend()->insertHeadTags($html, $uniquenessID); + Requirements::backend()->insertHeadTags($html, $uniquenessID); } /** @@ -199,7 +199,7 @@ class Requirements implements Flushable */ public static function javascriptTemplate($file, $vars, $uniquenessID = null) { - self::backend()->javascriptTemplate($file, $vars, $uniquenessID); + Requirements::backend()->javascriptTemplate($file, $vars, $uniquenessID); } /** @@ -214,7 +214,7 @@ class Requirements implements Flushable */ public static function css($file, $media = null, $options = []) { - self::backend()->css($file, $media, $options); + Requirements::backend()->css($file, $media, $options); } /** @@ -230,7 +230,7 @@ class Requirements implements Flushable */ public static function themedCSS($name, $media = null) { - self::backend()->themedCSS($name, $media); + Requirements::backend()->themedCSS($name, $media); } /** @@ -246,7 +246,7 @@ class Requirements implements Flushable */ public static function themedJavascript($name, $type = null) { - self::backend()->themedJavascript($name, $type); + Requirements::backend()->themedJavascript($name, $type); } /** @@ -259,7 +259,7 @@ class Requirements implements Flushable */ public static function clear($fileOrID = null) { - self::backend()->clear($fileOrID); + Requirements::backend()->clear($fileOrID); } /** @@ -267,7 +267,7 @@ class Requirements implements Flushable */ public static function restore() { - self::backend()->restore(); + Requirements::backend()->restore(); } /** @@ -285,7 +285,7 @@ class Requirements implements Flushable */ public static function block($fileOrID) { - self::backend()->block($fileOrID); + Requirements::backend()->block($fileOrID); } /** @@ -295,7 +295,7 @@ class Requirements implements Flushable */ public static function unblock($fileOrID) { - self::backend()->unblock($fileOrID); + Requirements::backend()->unblock($fileOrID); } /** @@ -303,7 +303,7 @@ class Requirements implements Flushable */ public static function unblock_all() { - self::backend()->unblockAll(); + Requirements::backend()->unblockAll(); } /** @@ -317,7 +317,7 @@ class Requirements implements Flushable */ public static function includeInHTML($content) { - return self::backend()->includeInHTML($content); + return Requirements::backend()->includeInHTML($content); } /** @@ -328,7 +328,7 @@ class Requirements implements Flushable */ public static function include_in_response(HTTPResponse $response) { - self::backend()->includeInResponse($response); + Requirements::backend()->includeInResponse($response); } /** @@ -345,7 +345,7 @@ class Requirements implements Flushable */ 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 @@ class Requirements implements Flushable 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 @@ class Requirements implements Flushable */ public static function get_combine_files() { - return self::backend()->getCombinedFiles(); + return Requirements::backend()->getCombinedFiles(); } /** @@ -420,7 +420,7 @@ class Requirements implements Flushable */ public static function delete_all_combined_files() { - self::backend()->deleteAllCombinedFiles(); + Requirements::backend()->deleteAllCombinedFiles(); } /** @@ -428,7 +428,7 @@ class Requirements implements Flushable */ public static function clear_combined_files() { - self::backend()->clearCombinedFiles(); + Requirements::backend()->clearCombinedFiles(); } /** @@ -436,7 +436,7 @@ class Requirements implements Flushable */ public static function process_combined_files() { - self::backend()->processCombinedFiles(); + Requirements::backend()->processCombinedFiles(); } /** @@ -447,7 +447,7 @@ class Requirements implements Flushable */ public static function get_write_js_to_body() { - return self::backend()->getWriteJavascriptToBody(); + return Requirements::backend()->getWriteJavascriptToBody(); } /** @@ -458,7 +458,7 @@ class Requirements implements Flushable */ public static function set_write_js_to_body($var) { - self::backend()->setWriteJavascriptToBody($var); + Requirements::backend()->setWriteJavascriptToBody($var); } /** @@ -469,7 +469,7 @@ class Requirements implements Flushable */ public static function get_force_js_to_bottom() { - return self::backend()->getForceJSToBottom(); + return Requirements::backend()->getForceJSToBottom(); } /** @@ -480,7 +480,7 @@ class Requirements implements Flushable */ public static function set_force_js_to_bottom($var) { - self::backend()->setForceJSToBottom($var); + Requirements::backend()->setForceJSToBottom($var); } /** @@ -490,7 +490,7 @@ class Requirements implements Flushable */ public static function get_minify_combined_js_files() { - return self::backend()->getMinifyCombinedJSFiles(); + return Requirements::backend()->getMinifyCombinedJSFiles(); } /** @@ -500,7 +500,7 @@ class Requirements implements Flushable */ public static function set_minify_combined_js_files($minify) { - self::backend()->setMinifyCombinedJSFiles($minify); + Requirements::backend()->setMinifyCombinedJSFiles($minify); } /** @@ -510,7 +510,7 @@ class Requirements implements Flushable */ public static function get_write_header_comments() { - return self::backend()->getWriteHeaderComment(); + return Requirements::backend()->getWriteHeaderComment(); } /** @@ -520,7 +520,7 @@ class Requirements implements Flushable */ public function set_write_header_comments($write) { - self::backend()->setWriteHeaderComment($write); + Requirements::backend()->setWriteHeaderComment($write); } @@ -529,6 +529,6 @@ class Requirements implements Flushable */ public static function debug() { - self::backend()->debug(); + Requirements::backend()->debug(); } } diff --git a/src/View/SSViewer.php b/src/View/SSViewer.php index c74766515..3b82eb3fd 100644 --- a/src/View/SSViewer.php +++ b/src/View/SSViewer.php @@ -194,7 +194,7 @@ class SSViewer implements Flushable $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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 @@ class SSViewer implements Flushable */ 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 4735bba01..7c5b6e5ec 100644 --- a/src/View/SSViewer_DataPresenter.php +++ b/src/View/SSViewer_DataPresenter.php @@ -79,11 +79,11 @@ class SSViewer_DataPresenter extends SSViewer_Scope */ 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 @@ class SSViewer_DataPresenter extends SSViewer_Scope */ 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 @@ class SSViewer_DataPresenter extends SSViewer_Scope } // 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 @@ class SSViewer_DataPresenter extends SSViewer_Scope } // 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 3b0fe1a5e..36af637bd 100644 --- a/src/View/SSViewer_Scope.php +++ b/src/View/SSViewer_Scope.php @@ -136,7 +136,7 @@ class SSViewer_Scope /** * 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() { @@ -258,7 +258,7 @@ class SSViewer_Scope /** * 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() { @@ -280,7 +280,7 @@ class SSViewer_Scope /** * 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 9a8c52450..89806d6bc 100644 --- a/src/View/Shortcodes/EmbedShortcodeProvider.php +++ b/src/View/Shortcodes/EmbedShortcodeProvider.php @@ -200,7 +200,7 @@ class EmbedShortcodeProvider implements ShortcodeHandler '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 @@ class EmbedShortcodeProvider implements ShortcodeHandler '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 @@ class EmbedShortcodeProvider implements ShortcodeHandler 'Src' => $src ]; - return ArrayData::create($data)->renderWith(self::class . '_photo')->forTemplate(); + return ArrayData::create($data)->renderWith(EmbedShortcodeProvider::class . '_photo')->forTemplate(); } /** @@ -327,10 +327,10 @@ class EmbedShortcodeProvider implements ShortcodeHandler { 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 f764d71a1..402ac4aa6 100644 --- a/src/View/ThemeManifest.php +++ b/src/View/ThemeManifest.php @@ -161,7 +161,7 @@ class ThemeManifest implements ThemeList */ 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 7967c22bd..8799fe13a 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 @@ class ThemeResourceLoader implements Flushable, TemplateGlobalProvider */ public static function set_instance(ThemeResourceLoader $instance) { - self::$instance = $instance; + ThemeResourceLoader::$instance = $instance; } public function __construct($base = null) @@ -390,7 +390,7 @@ class ThemeResourceLoader implements Flushable, TemplateGlobalProvider */ 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 f5f19ec8c..d729d36da 100644 --- a/src/View/ViewableData.php +++ b/src/View/ViewableData.php @@ -267,7 +267,7 @@ class ViewableData implements IteratorAggregate 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 @@ class ViewableData implements IteratorAggregate 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 @@ class ViewableData implements IteratorAggregate */ 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 @@ class ViewableData implements IteratorAggregate * @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 fce88716d..3d3d6fa6f 100644 --- a/src/i18n/TextCollection/i18nTextCollector.php +++ b/src/i18n/TextCollection/i18nTextCollector.php @@ -474,7 +474,7 @@ class i18nTextCollector 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 @@ class i18nTextCollector */ 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 @@ class i18nTextCollector $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 @@ class i18nTextCollector $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 @@ class i18nTextCollector // 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 @@ class i18nTextCollector continue; } - // Start collecting self::class declarations + // Start collecting i18nTextCollector::class declarations if ($id === T_STRING && $text === 'self') { $inSelf = true; continue; @@ -770,7 +770,7 @@ class i18nTextCollector 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 5f0b6f3f9..61ab1ec15 100644 --- a/src/i18n/i18n.php +++ b/src/i18n/i18n.php @@ -264,7 +264,7 @@ class i18n implements TemplateGlobalProvider 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 @@ class i18n implements TemplateGlobalProvider public static function set_locale($locale) { if ($locale) { - self::$current_locale = $locale; + i18n::$current_locale = $locale; } } @@ -321,7 +321,7 @@ class i18n implements TemplateGlobalProvider */ 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 @@ class i18n implements TemplateGlobalProvider */ 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 7a28aa6ba..f1c290e16 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 b9150f29d..8392dd495 100644 --- a/tests/php/Control/RSS/RSSFeedTest.php +++ b/tests/php/Control/RSS/RSSFeedTest.php @@ -100,8 +100,8 @@ class RSSFeedTest extends SapphireTest { 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 @@ class RSSFeedTest extends SapphireTest 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 44c849a51..089e43a16 100644 --- a/tests/php/Control/RequestHandlingTest/ControllerExtension.php +++ b/tests/php/Control/RequestHandlingTest/ControllerExtension.php @@ -27,7 +27,7 @@ class ControllerExtension extends Extension implements TestOnly */ public function onBeforeHTTPError() { - self::$called_error = true; + ControllerExtension::$called_error = true; } /** @@ -35,6 +35,6 @@ class ControllerExtension extends Extension implements TestOnly */ 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 e2db8f78f..e73ee27cc 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 7cbd2d276..3dcda9471 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 922a46c48..bb33b86b4 100644 --- a/tests/php/Dev/SapphireTestTest/DataProvider.php +++ b/tests/php/Dev/SapphireTestTest/DataProvider.php @@ -32,7 +32,7 @@ class DataProvider implements TestOnly [], ], ], - self::provideEqualLists() + DataProvider::provideEqualLists() ); } @@ -46,34 +46,34 @@ class DataProvider implements TestOnly [ ['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 @@ class DataProvider implements TestOnly [ ['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 @@ class DataProvider implements TestOnly [ ['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 @@ class DataProvider implements TestOnly 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 @@ class DataProvider implements TestOnly 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 fb36b91d1..1aa90eac2 100644 --- a/tests/php/Logging/DetailedErrorFormatterTest.php +++ b/tests/php/Logging/DetailedErrorFormatterTest.php @@ -43,7 +43,7 @@ class DetailedErrorFormatterTest extends SapphireTest $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 65950a9ae..13c2460c8 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 @@ class DataListEagerLoadingTest extends SapphireTest */ 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 @@ class DataListEagerLoadingTest extends SapphireTest */ 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 @@ class DataListEagerLoadingTest extends SapphireTest } 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 fc863f512..fc8ed726a 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 e497748b2..43a6535c7 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 @@ class TreeNode extends DataObject implements TestOnly 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 ea5d51d4d..d8825d26c 100644 --- a/tests/php/ORM/Filters/EndsWithFilterTest.php +++ b/tests/php/ORM/Filters/EndsWithFilterTest.php @@ -5,6 +5,7 @@ namespace SilverStripe\ORM\Tests\Filters; 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 @@ class EndsWithFilterTest extends SapphireTest } } - 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 aa66b2641..61cf04d42 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\Task; 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 @@ class ExactMatchFilterTest extends SapphireTest } } - 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 8f39248b3..f4ad89942 100644 --- a/tests/php/ORM/Filters/PartialMatchFilterTest.php +++ b/tests/php/ORM/Filters/PartialMatchFilterTest.php @@ -5,6 +5,7 @@ namespace SilverStripe\ORM\Tests\Filters; 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 @@ class PartialMatchFilterTest extends SapphireTest } } - 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 5d4cac344..855020f53 100644 --- a/tests/php/ORM/Filters/StartsWithFilterTest.php +++ b/tests/php/ORM/Filters/StartsWithFilterTest.php @@ -5,6 +5,7 @@ namespace SilverStripe\ORM\Tests\Filters; 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 @@ class StartsWithFilterTest extends SapphireTest } } - 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 104efe472..e2af6cffd 100644 --- a/tests/php/ORM/MarkedSetTest.php +++ b/tests/php/ORM/MarkedSetTest.php @@ -394,7 +394,7 @@ EOT; $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 @@ EOT; $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 0a46b0e91..8da8b65dd 100644 --- a/tests/php/ORM/MySQLiConnectorTest.php +++ b/tests/php/ORM/MySQLiConnectorTest.php @@ -62,7 +62,7 @@ class MySQLiConnectorTest extends SapphireTest implements TestOnly // 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 dd1988698..93efd4b5e 100644 --- a/tests/php/ORM/RelatedDataServiceTest.php +++ b/tests/php/ORM/RelatedDataServiceTest.php @@ -109,7 +109,7 @@ class RelatedDataServiceTest extends SapphireTest // 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 @@ class RelatedDataServiceTest extends SapphireTest // 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 6423b2e12..93a151569 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 066ff9ca0..a3e59caf6 100644 --- a/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php +++ b/tests/php/Security/InheritedPermissionsFlusherTest/TestCacheFlusher.php @@ -47,7 +47,7 @@ class TestCacheFlusher implements MemberCacheFlusher } 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 f769a4802..1621f40ed 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 db45f0831..ab816bbd1 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 c2582de9e..30838d4eb 100644 --- a/tests/php/View/RequirementsTest.php +++ b/tests/php/View/RequirementsTest.php @@ -62,7 +62,7 @@ class RequirementsTest extends SapphireTest $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 @@ class RequirementsTest extends SapphireTest ] ); - $backend->includeInHTML(self::$html_template); + $backend->includeInHTML(RequirementsTest::$html_template); // we get the file path here $allCSS = $backend->getCSS(); @@ -137,7 +137,7 @@ class RequirementsTest extends SapphireTest ] ); - $backend->includeInHTML(self::$html_template); + $backend->includeInHTML(RequirementsTest::$html_template); // we get the file path here $allCSS = $backend->getCSS(); @@ -389,7 +389,7 @@ class RequirementsTest extends SapphireTest [ 'type' => 'application/json' ] ); $backend->javascript('javascript/RequirementsTest_b.js'); - $result = $backend->includeInHTML(self::$html_template); + $result = $backend->includeInHTML(RequirementsTest::$html_template); $this->assertMatchesRegularExpression( '#