ENH PHP 8.1 compatibility

This commit is contained in:
Steve Boyd 2022-04-13 13:52:56 +12:00
parent cd0deae9c0
commit 792d61fded
21 changed files with 71 additions and 71 deletions

View File

@ -124,14 +124,14 @@ class UserDefinedFormController extends PageController
{
$form = $this->Form();
if ($this->Content && $form && !$this->config()->disable_form_content_shortcode) {
$hasLocation = stristr($this->Content, '$UserDefinedForm');
$hasLocation = stristr($this->Content ?? '', '$UserDefinedForm');
if ($hasLocation) {
/** @see Requirements_Backend::escapeReplacement */
$formEscapedForRegex = addcslashes($form->forTemplate(), '\\$');
$formEscapedForRegex = addcslashes($form->forTemplate() ?? '', '\\$');
$content = preg_replace(
'/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i',
$formEscapedForRegex,
$this->Content
$formEscapedForRegex ?? '',
$this->Content ?? ''
);
return [
'Content' => DBField::create_field('HTMLText', $content),
@ -260,7 +260,7 @@ JS
$submittedField->Displayed = $field->isDisplayed($data);
if (!empty($data[$field->Name])) {
if (in_array(EditableFileField::class, $field->getClassAncestry())) {
if (in_array(EditableFileField::class, $field->getClassAncestry() ?? [])) {
if (!empty($_FILES[$field->Name]['name'])) {
$foldername = $field->getFormField()->getFolderName();
@ -371,15 +371,15 @@ JS
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name);
if ($submittedFormField && $submittedFormField->Value && is_string($submittedFormField->Value)) {
$email->setReplyTo(explode(',', $submittedFormField->Value));
$email->setReplyTo(explode(',', $submittedFormField->Value ?? ''));
}
} elseif ($recipient->EmailReplyTo) {
$email->setReplyTo(explode(',', $recipient->EmailReplyTo));
$email->setReplyTo(explode(',', $recipient->EmailReplyTo ?? ''));
}
// check for a specified from; otherwise fall back to server defaults
if ($recipient->EmailFrom) {
$email->setFrom(explode(',', $recipient->EmailFrom));
$email->setFrom(explode(',', $recipient->EmailFrom ?? ''));
}
// check to see if they are a dynamic reciever eg based on a dropdown field a user selected
@ -390,12 +390,12 @@ JS
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name);
if ($submittedFormField && is_string($submittedFormField->Value)) {
$email->setTo(explode(',', $submittedFormField->Value));
$email->setTo(explode(',', $submittedFormField->Value ?? ''));
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
$email->setTo(explode(',', $recipient->EmailAddress ?? ''));
}
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
$email->setTo(explode(',', $recipient->EmailAddress ?? ''));
}
} catch (Swift_RfcComplianceException $e) {
// The sending address is empty and/or invalid. Log and skip sending.
@ -415,7 +415,7 @@ JS
if ($emailSubject && $emailSubject->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name);
if ($submittedFormField && trim($submittedFormField->Value)) {
if ($submittedFormField && trim($submittedFormField->Value ?? '')) {
$email->setSubject($submittedFormField->Value);
} else {
$email->setSubject(SSViewer::execute_string($recipient->EmailSubject, $mergeFields));
@ -428,7 +428,7 @@ JS
if ((bool)$recipient->SendPlain) {
// decode previously encoded html tags because the email is being sent as text/plain
$body = html_entity_decode($emailData['Body']) . "\n";
$body = html_entity_decode($emailData['Body'] ?? '') . "\n";
if (isset($emailData['Fields']) && !$emailData['HideFormData']) {
foreach ($emailData['Fields'] as $field) {
if ($field instanceof SubmittedFileField) {
@ -474,7 +474,7 @@ JS
// to allow us to get through the finshed method
if (!$this->Form()->getSecurityToken()->isEnabled()) {
$randNum = rand(1, 1000);
$randHash = md5($randNum);
$randHash = md5($randNum ?? '');
$session->set('FormProcessed', $randHash);
$session->set('FormProcessedNum', $randNum);
}
@ -531,7 +531,7 @@ JS
// make sure the session matches the SecurityID and is not left over from another form
if ($formProcessed != $securityID) {
// they may have disabled tokens on the form
$securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum'));
$securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum') ?? '');
if ($formProcessed != $securityID) {
return $this->redirect($this->Link() . $referrer);
}
@ -571,7 +571,7 @@ JS
$operations = implode(" {$conjunction} ", $rule['operations']);
$target = $rule['targetFieldID'];
$holder = $rule['holder'];
$isFormStep = strpos($target, 'EditableFormStep') !== false;
$isFormStep = strpos($target ?? '', 'EditableFormStep') !== false;
$result .= <<<EOS
\n
@ -592,7 +592,7 @@ EOS;
// This is particularly important beacause the next/prev page buttons logic is controlled by
// the visibility of the FormStep buttons
// The HTML for the FormStep buttons is defined in UserFormProgress.ss
$id = str_replace('#', '', $target);
$id = str_replace('#', '', $target ?? '');
$result .= <<<EOS
$('.step-button-wrapper[data-for="{$id}"]').addClass('hide');
EOS;

View File

@ -67,7 +67,7 @@ class UpgradePolymorphicExtension extends DataExtension
// If the defined data class doesn't have the UserForm trait applied, it's probably wrong. Re-map
// it to a default value that does
$classTraits = class_uses($relationshipObject);
if (in_array(UserForm::class, $classTraits)) {
if (in_array(UserForm::class, $classTraits ?? [])) {
continue;
}

View File

@ -29,7 +29,7 @@ class UserFormValidator extends RequiredFields
foreach ($fields as $field) {
if ($field instanceof EditableFormStep) {
// Page at top level, or after another page is ok
if (empty($stack) || (count($stack) === 1 && $stack[0] instanceof EditableFormStep)) {
if (empty($stack) || (count($stack ?? []) === 1 && $stack[0] instanceof EditableFormStep)) {
$stack = array($field);
$conditionalStep = $field->DisplayRules()->count() > 0;
continue;

View File

@ -145,7 +145,7 @@ class GridFieldAddClassesButton implements GridField_HTMLProvider, GridField_Act
}
// Filter out classes without permission
return array_filter($classes, function ($class) {
return array_filter($classes ?? [], function ($class) {
return singleton($class)->canCreate();
});
}
@ -219,7 +219,7 @@ class GridFieldAddClassesButton implements GridField_HTMLProvider, GridField_Act
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
switch (strtolower($actionName)) {
switch (strtolower($actionName ?? '')) {
case $this->getAction():
return $this->handleAdd($gridField);
default:

View File

@ -122,7 +122,7 @@ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader
$actions->addExtraClass('no-change-track');
$colSpan = 2 + count($gridField->getConfig()->getComponentByType(GridFieldDataColumns::class)
->getDisplayFields($gridField));
->getDisplayFields($gridField) ?? []);
$forTemplate = ArrayData::create(array(
'Fields' => $fields,

View File

@ -113,11 +113,11 @@ class UserFormsRequiredFields extends RequiredFields
if ($field instanceof FileField && isset($value['error']) && $value['error']) {
$error = true;
} else {
$error = (count($value)) ? false : true;
$error = (count($value ?? [])) ? false : true;
}
} else {
// assume a string or integer
$error = (strlen($value)) ? false : true;
$error = (strlen($value ?? '')) ? false : true;
}
return $error;

View File

@ -24,7 +24,7 @@ class UserFormsCheckboxSetField extends CheckboxSetField
*/
public function getValidationAttributesHTML()
{
$attrs = array_filter(array_keys($this->getAttributes()), function ($attr) {
$attrs = array_filter(array_keys($this->getAttributes() ?? []), function ($attr) {
return !in_array($attr, ['data-rule-required', 'data-msg-required']);
});
return $this->getAttributesHTML(...$attrs);
@ -60,8 +60,8 @@ class UserFormsCheckboxSetField extends CheckboxSetField
$previous = $value = $this->Value();
if (is_string($value) && strstr($value, ",")) {
$value = explode(",", $value);
if (is_string($value) && strstr($value ?? '', ",")) {
$value = explode(",", $value ?? '');
}
// set the value as an array for parent validation

View File

@ -43,7 +43,7 @@ class UserFormsFieldList extends FieldList implements UserFormsFieldContainer
public function clearEmptySteps()
{
foreach ($this as $field) {
if ($field instanceof UserFormsStepField && count($field->getChildren()) === 0) {
if ($field instanceof UserFormsStepField && count($field->getChildren() ?? []) === 0) {
$this->remove($field);
}
}

View File

@ -24,7 +24,7 @@ class UserFormsOptionSetField extends OptionsetField
*/
public function getValidationAttributesHTML()
{
$attrs = array_filter(array_keys($this->getAttributes()), function ($attr) {
$attrs = array_filter(array_keys($this->getAttributes() ?? []), function ($attr) {
return !in_array($attr, ['data-rule-required', 'data-msg-required']);
});
return $this->getAttributesHTML(...$attrs);

View File

@ -299,7 +299,7 @@ class EditableCustomRule extends DataObject
*/
public function toggleDisplayText($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'removeClass' : 'addClass';
$action = strtolower($initialState ?? '') === 'hide' ? 'removeClass' : 'addClass';
if ($invert) {
$action = $action === 'removeClass' ? 'addClass' : 'removeClass';
}
@ -316,7 +316,7 @@ class EditableCustomRule extends DataObject
*/
public function toggleDisplayEvent($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'show' : 'hide';
$action = strtolower($initialState ?? '') === 'hide' ? 'show' : 'hide';
if ($invert) {
$action = $action === 'hide' ? 'show' : 'hide';
}

View File

@ -358,7 +358,7 @@ class EditableFormField extends DataObject
*/
protected function getDisplayRuleFields()
{
$allowedClasses = array_keys($this->getEditableFieldClasses(false));
$allowedClasses = array_keys($this->getEditableFieldClasses(false) ?? []);
$editableColumns = new GridFieldEditableColumns();
$editableColumns->setDisplayFields([
'ConditionFieldID' => function ($record, $column, $grid) use ($allowedClasses) {
@ -584,7 +584,7 @@ class EditableFormField extends DataObject
return false;
}
return stripos($this->ID, 'new') === 0;
return stripos($this->ID ?? '', 'new') === 0;
}
/**
@ -612,7 +612,7 @@ class EditableFormField extends DataObject
$shortClass = end($classNamespaces);
$resource = ModuleLoader::getModule('silverstripe/userforms')
->getResource('images/' . strtolower($shortClass) . '.png');
->getResource('images/' . strtolower($shortClass ?? '') . '.png');
if (!$resource->exists()) {
return '';
@ -782,7 +782,7 @@ class EditableFormField extends DataObject
}
// if this field has a placeholder
if (strlen($this->Placeholder) >= 0) {
if (strlen($this->Placeholder ?? '') >= 0) {
$field->setAttribute('placeholder', $this->Placeholder);
}
}
@ -983,10 +983,10 @@ class EditableFormField extends DataObject
$fieldToWatch = $formFieldWatch->getSelectorFieldOnly();
$expression = $rule->buildExpression();
if (!in_array($fieldToWatch, $result['selectors'])) {
if (!in_array($fieldToWatch, $result['selectors'] ?? [])) {
$result['selectors'][] = $fieldToWatch;
}
if (!in_array($expression['event'], $result['events'])) {
if (!in_array($expression['event'], $result['events'] ?? [])) {
$result['events'][] = $expression['event'];
}
$result['operations'][] = $expression['operation'];
@ -999,7 +999,7 @@ class EditableFormField extends DataObject
$result['holder_event_opposite'] = $rule->toggleDisplayEvent($result['initialState'], true);
}
return (count($result['selectors'])) ? $result : null;
return (count($result['selectors'] ?? [])) ? $result : null;
}
/**
@ -1050,7 +1050,7 @@ class EditableFormField extends DataObject
*/
public function DisplayRulesConjunctionNice()
{
return (strtolower($this->DisplayRulesConjunction) === 'or') ? '||' : '&&';
return (strtolower($this->DisplayRulesConjunction ?? '') === 'or') ? '||' : '&&';
}
/**

View File

@ -209,7 +209,7 @@ class EditableFileField extends EditableFormField
$field->getValidator()->setAllowedExtensions(
array_diff(
// filter out '' since this would be a regex problem on JS end
array_filter(Config::inst()->get(File::class, 'allowed_extensions')),
array_filter(Config::inst()->get(File::class, 'allowed_extensions') ?? []),
$this->config()->get('allowed_extensions_blacklist')
)
);
@ -223,7 +223,7 @@ class EditableFileField extends EditableFormField
$folder = $this->Folder();
if ($folder && $folder->exists()) {
$field->setFolderName(
preg_replace("/^assets\//", "", $folder->Filename)
preg_replace("/^assets\//", "", $folder->Filename ?? '')
);
}

View File

@ -143,9 +143,9 @@ class EmailRecipient extends DataObject
// email addresses have trim() applied to them during validation for a slightly nicer UX
// apply trim() here too before saving to the database
$this->EmailAddress = trim($this->EmailAddress);
$this->EmailFrom = trim($this->EmailFrom);
$this->EmailReplyTo = trim($this->EmailReplyTo);
$this->EmailAddress = trim($this->EmailAddress ?? '');
$this->EmailFrom = trim($this->EmailFrom ?? '');
$this->EmailReplyTo = trim($this->EmailReplyTo ?? '');
}
public function summaryFields()
@ -272,9 +272,9 @@ class EmailRecipient extends DataObject
// an AJAX request, e.g. saving a GridFieldDetailForm
$remove = ['/edit', '/ItemEditForm'];
foreach ($remove as $badSuffix) {
$badSuffixLength = strlen($badSuffix);
if (substr($currentUrl, -$badSuffixLength) === $badSuffix) {
$currentUrl = substr($currentUrl, 0, -$badSuffixLength);
$badSuffixLength = strlen($badSuffix ?? '');
if (substr($currentUrl ?? '', -$badSuffixLength) === $badSuffix) {
$currentUrl = substr($currentUrl ?? '', 0, -$badSuffixLength);
}
}
$previewUrl = Controller::join_links($currentUrl, 'preview');
@ -534,7 +534,7 @@ class EmailRecipient extends DataObject
$found = $finder->find(BASE_PATH . DIRECTORY_SEPARATOR . $templateDirectory);
foreach ($found as $key => $value) {
$template = pathinfo($value);
$template = pathinfo($value ?? '');
$absoluteFilename = $template['dirname'] . DIRECTORY_SEPARATOR . $template['filename'];
// Optionally remove vendor/ path prefixes
@ -544,10 +544,10 @@ class EmailRecipient extends DataObject
} else {
$prefixToStrip = BASE_PATH;
}
$templatePath = substr($absoluteFilename, strlen($prefixToStrip) + 1);
$templatePath = substr($absoluteFilename ?? '', strlen($prefixToStrip ?? '') + 1);
// Optionally remove "templates/" ("templates\" on Windows respectively) prefixes
if (preg_match('#(?<=templates' . preg_quote(DIRECTORY_SEPARATOR, '#') . ').*$#', $templatePath, $matches)) {
if (preg_match('#(?<=templates' . preg_quote(DIRECTORY_SEPARATOR, '#') . ').*$#', $templatePath ?? '', $matches)) {
$templatePath = $matches[0];
}
@ -573,9 +573,9 @@ class EmailRecipient extends DataObject
foreach ($checkEmail as $check => $translation) {
if ($this->$check) {
//may be a comma separated list of emails
$addresses = explode(',', $this->$check);
$addresses = explode(',', $this->$check ?? '');
foreach ($addresses as $address) {
$trimAddress = trim($address);
$trimAddress = trim($address ?? '');
if ($trimAddress && !Email::is_valid_address($trimAddress)) {
$error = _t(
__CLASS__.".$translation",

View File

@ -8,11 +8,11 @@ class UnderscoreSegmentFieldModifier extends SlugSegmentFieldModifier
{
public function getPreview($value)
{
return str_replace('-', '_', parent::getPreview($value));
return str_replace('-', '_', parent::getPreview($value) ?? '');
}
public function getSuggestion($value)
{
return str_replace('-', '_', parent::getSuggestion($value));
return str_replace('-', '_', parent::getSuggestion($value) ?? '');
}
}

View File

@ -57,7 +57,7 @@ class UserFormsColumnCleanTask extends MigrationTask
DB::query($query);
$backedUp = 1;
}
if (!isset($columns[$column]) && !in_array($column, $this->keepColumns)) {
if (!isset($columns[$column]) && !in_array($column, $this->keepColumns ?? [])) {
echo "Dropping $column from $db <br />";
$query = "ALTER TABLE $db DROP COLUMN $column";
DB::query($query);

View File

@ -255,7 +255,7 @@ SQL;
$columns = array();
foreach (DB::query($columnSQL)->map() as $name => $title) {
$columns[$name] = trim(strtr($title, '.', ' '));
$columns[$name] = trim(strtr($title ?? '', '.', ' '));
}
$config = GridFieldConfig::create();

View File

@ -106,7 +106,7 @@ class UserDefinedFormAdminTest extends FunctionalTest
null,
['X-FormSchema-Request' => 'auto,schema,state,errors']
);
$schemaData = json_decode($response->getBody(), true);
$schemaData = json_decode($response->getBody() ?? '', true);
$this->assertEquals('ConfirmFolderForm', $schemaData['schema']['name']);
$this->assertField($schemaData, 'FolderOptions', ['component' => 'OptionsetField']);
@ -128,7 +128,7 @@ class UserDefinedFormAdminTest extends FunctionalTest
null,
['X-FormSchema-Request' => 'auto,schema,state,errors']
);
$schemaData = json_decode($response->getBody(), true);
$schemaData = json_decode($response->getBody() ?? '', true);
$this->assertEquals('ConfirmFolderForm', $schemaData['schema']['name']);
$this->assertField($schemaData, 'FolderOptions', ['component' => 'OptionsetField']);

View File

@ -96,7 +96,7 @@ class UserDefinedFormControllerTest extends FunctionalTest
// submitted html tags are escaped for the html value
$value = 'class="readonly">My body html Basic Value &lt;b&gt;HTML&lt;/b&gt;</span>';
$this->assertTrue(strpos($email['Content'], $value) !== false, 'Email contains the merge field value');
$this->assertTrue(strpos($email['Content'] ?? '', $value ?? '') !== false, 'Email contains the merge field value');
$value = $parser->getBySelector('dd');
$this->assertEquals('Basic Value <b>HTML</b>', (string) $value[0], 'Email contains the value');
@ -198,14 +198,14 @@ class UserDefinedFormControllerTest extends FunctionalTest
$this->assertEquals($controller->Form()->getName(), 'Form_' . $form->ID, 'The form is referenced as Form');
$this->assertEquals($controller->Form()->Fields()->Count(), 1); // disabled SecurityID token fields
$this->assertEquals($controller->Form()->Actions()->Count(), 1);
$this->assertEquals(count($controller->Form()->getValidator()->getRequired()), 0);
$this->assertEquals(count($controller->Form()->getValidator()->getRequired() ?? []), 0);
$requiredForm = $this->objFromFixture(UserDefinedForm::class, 'validation-form');
$controller = new UserDefinedFormController($requiredForm);
$this->assertEquals($controller->Form()->Fields()->Count(), 1); // disabled SecurityID token fields
$this->assertEquals($controller->Form()->Actions()->Count(), 1);
$this->assertEquals(count($controller->Form()->getValidator()->getRequired()), 1);
$this->assertEquals(count($controller->Form()->getValidator()->getRequired() ?? []), 1);
}
public function testGetFormFields()
@ -413,7 +413,7 @@ class UserDefinedFormControllerTest extends FunctionalTest
'type' => 'image/jpeg',
'tmp_name' => $path,
'error' => 0,
'size' => filesize($path),
'size' => filesize($path ?? ''),
]
];
$_FILES[$field->Name] = $data[$field->Name];
@ -449,7 +449,7 @@ class UserDefinedFormControllerTest extends FunctionalTest
'type' => 'image/jpeg',
'tmp_name' => $path,
'error' => 0,
'size' => filesize($path),
'size' => filesize($path ?? ''),
]
];
$_FILES[$field->Name] = $data[$field->Name];

View File

@ -46,6 +46,6 @@ class UserFormsCheckboxSetFieldTest extends SapphireTest
$userFormsCheckboxSetField = $editableCheckboxGroupField->getFormField();
$html = $userFormsCheckboxSetField->renderWith(UserFormsCheckboxSetField::class)->getValue();
$attributesHTML = 'data-rule-required="true" data-msg-required="My custom error message with &amp;#039;single&amp;#039; and &amp;quot;double&amp;quot; quotes"';
$this->assertTrue(strpos($html, $attributesHTML) > 0);
$this->assertTrue(strpos($html ?? '', $attributesHTML ?? '') > 0);
}
}

View File

@ -19,6 +19,6 @@ class UserFormsOptionSetFieldTest extends SapphireTest
$userFormsOptionSetField = $radio->getFormField();
$html = $userFormsOptionSetField->renderWith(UserFormsOptionSetField::class)->getValue();
$attributesHTML = 'data-rule-required="true" data-msg-required="My custom error message with &amp;#039;single&amp;#039; and &amp;quot;double&amp;quot; quotes"';
$this->assertTrue(strpos($html, $attributesHTML) > 0);
$this->assertTrue(strpos($html ?? '', $attributesHTML ?? '') > 0);
}
}

View File

@ -100,8 +100,8 @@ class UserDefinedFormTest extends FunctionalTest
$summaryFields = $gridFieldDataColumns->getDisplayFields($submissionsgrid);
$this->assertContains('SummaryShow', array_keys($summaryFields), 'Summary field not showing displayed field');
$this->assertNotContains('SummaryHide', array_keys($summaryFields), 'Summary field showing displayed field');
$this->assertContains('SummaryShow', array_keys($summaryFields ?? []), 'Summary field not showing displayed field');
$this->assertNotContains('SummaryHide', array_keys($summaryFields ?? []), 'Summary field showing displayed field');
}
public function testEmailRecipientPopup()
@ -177,13 +177,13 @@ class UserDefinedFormTest extends FunctionalTest
// Installation path can be as a project when testing in Travis, so check partial match
$foundKey = false;
foreach (array_keys($result) as $key) {
if (strpos($key, 'email' . DIRECTORY_SEPARATOR . 'SubmittedFormEmail') !== false) {
foreach (array_keys($result ?? []) as $key) {
if (strpos($key ?? '', 'email' . DIRECTORY_SEPARATOR . 'SubmittedFormEmail') !== false) {
$foundKey = true;
}
}
$this->assertTrue($foundKey);
$this->assertTrue(in_array('SubmittedFormEmail', array_values($result)));
$this->assertTrue(in_array('SubmittedFormEmail', array_values($result ?? [])));
}
public function testEmailTemplateExists()
@ -195,7 +195,7 @@ class UserDefinedFormTest extends FunctionalTest
$recipient->EmailAddress = 'test@example.com';
// Set the default template
$recipient->EmailTemplate = current(array_keys($recipient->getEmailTemplateDropdownValues()));
$recipient->EmailTemplate = current(array_keys($recipient->getEmailTemplateDropdownValues() ?? []));
$recipient->write();
// The default template exists