Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH PHP 8.1 compatibility #1141

Merged
merged 1 commit into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions code/Control/UserDefinedFormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,14 @@ public function index(HTTPRequest $request = null)
{
$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),
Expand Down Expand Up @@ -260,7 +260,7 @@ public function process($data, $form)
$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();

Expand Down Expand Up @@ -371,15 +371,15 @@ public function process($data, $form)
$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
Expand All @@ -390,12 +390,12 @@ public function process($data, $form)
$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.
Expand All @@ -415,7 +415,7 @@ public function process($data, $form)
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));
Expand All @@ -428,7 +428,7 @@ public function process($data, $form)

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) {
Expand Down Expand Up @@ -474,7 +474,7 @@ public function process($data, $form)
// 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);
}
Expand Down Expand Up @@ -531,7 +531,7 @@ public function finished()
// 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);
}
Expand Down Expand Up @@ -571,7 +571,7 @@ protected function buildWatchJS($watch)
$operations = implode(" {$conjunction} ", $rule['operations']);
$target = $rule['targetFieldID'];
$holder = $rule['holder'];
$isFormStep = strpos($target, 'EditableFormStep') !== false;
$isFormStep = strpos($target ?? '', 'EditableFormStep') !== false;

$result .= <<<EOS
\n
Expand All @@ -592,7 +592,7 @@ function (){
// 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;
Expand Down
2 changes: 1 addition & 1 deletion code/Extension/UpgradePolymorphicExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function requireDefaultRecords()
// 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;
}

Expand Down
2 changes: 1 addition & 1 deletion code/Extension/UserFormValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function php($data)
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;
Expand Down
4 changes: 2 additions & 2 deletions code/Form/GridFieldAddClassesButton.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function getClassesCreate($grid)
}

// Filter out classes without permission
return array_filter($classes, function ($class) {
return array_filter($classes ?? [], function ($class) {
return singleton($class)->canCreate();
});
}
Expand Down Expand Up @@ -219,7 +219,7 @@ protected function getAction()

public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
switch (strtolower($actionName)) {
switch (strtolower($actionName ?? '')) {
case $this->getAction():
return $this->handleAdd($gridField);
default:
Expand Down
2 changes: 1 addition & 1 deletion code/Form/UserFormsGridFieldFilterHeader.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function getHTMLFragments($gridField)
$actions->addExtraClass('no-change-track');

$colSpan = 2 + count($gridField->getConfig()->getComponentByType(GridFieldDataColumns::class)
->getDisplayFields($gridField));
->getDisplayFields($gridField) ?? []);

$forTemplate = ArrayData::create(array(
'Fields' => $fields,
Expand Down
4 changes: 2 additions & 2 deletions code/Form/UserFormsRequiredFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ private function validateRequired(FormField $field, array $data)
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;
Expand Down
6 changes: 3 additions & 3 deletions code/FormField/UserFormsCheckboxSetField.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -60,8 +60,8 @@ public function validate($validator)

$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
Expand Down
2 changes: 1 addition & 1 deletion code/FormField/UserFormsFieldList.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function setParent(UserFormsFieldContainer $parent)
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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion code/FormField/UserFormsOptionSetField.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions code/Model/EditableCustomRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ public function validateAgainstFormData(array $data)
*/
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';
}
Expand All @@ -316,7 +316,7 @@ public function toggleDisplayText($initialState, $invert = false)
*/
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';
}
Expand Down
16 changes: 8 additions & 8 deletions code/Model/EditableFormField.php
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ public function requireDefaultRecords()
*/
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) {
Expand Down Expand Up @@ -584,7 +584,7 @@ public function isNew()
return false;
}

return stripos($this->ID, 'new') === 0;
return stripos($this->ID ?? '', 'new') === 0;
}

/**
Expand Down Expand Up @@ -612,7 +612,7 @@ public function getIcon()
$shortClass = end($classNamespaces);

$resource = ModuleLoader::getModule('silverstripe/userforms')
->getResource('images/' . strtolower($shortClass) . '.png');
->getResource('images/' . strtolower($shortClass ?? '') . '.png');

if (!$resource->exists()) {
return '';
Expand Down Expand Up @@ -782,7 +782,7 @@ protected function updateFormField($field)
}

// if this field has a placeholder
if (strlen($this->Placeholder) >= 0) {
if (strlen($this->Placeholder ?? '') >= 0) {
$field->setAttribute('placeholder', $this->Placeholder);
}
}
Expand Down Expand Up @@ -983,10 +983,10 @@ public function formatDisplayRules()
$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'];
Expand All @@ -999,7 +999,7 @@ public function formatDisplayRules()
$result['holder_event_opposite'] = $rule->toggleDisplayEvent($result['initialState'], true);
}

return (count($result['selectors'])) ? $result : null;
return (count($result['selectors'] ?? [])) ? $result : null;
}

/**
Expand Down Expand Up @@ -1050,7 +1050,7 @@ public function isDisplayed(array $data)
*/
public function DisplayRulesConjunctionNice()
{
return (strtolower($this->DisplayRulesConjunction) === 'or') ? '||' : '&&';
return (strtolower($this->DisplayRulesConjunction ?? '') === 'or') ? '||' : '&&';
}

/**
Expand Down
4 changes: 2 additions & 2 deletions code/Model/EditableFormField/EditableFileField.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public function getFormField()
$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')
)
);
Expand All @@ -223,7 +223,7 @@ public function getFormField()
$folder = $this->Folder();
if ($folder && $folder->exists()) {
$field->setFolderName(
preg_replace("/^assets\//", "", $folder->Filename)
preg_replace("/^assets\//", "", $folder->Filename ?? '')
);
}

Expand Down
22 changes: 11 additions & 11 deletions code/Model/Recipient/EmailRecipient.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,9 @@ public function onBeforeWrite()

// 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()
Expand Down Expand Up @@ -272,9 +272,9 @@ public function getCMSFields()
// 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');
Expand Down Expand Up @@ -534,7 +534,7 @@ public function getEmailTemplateDropdownValues()
$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
Expand All @@ -544,10 +544,10 @@ public function getEmailTemplateDropdownValues()
} 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];
}

Expand All @@ -573,9 +573,9 @@ public function validate()
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",
Expand Down
4 changes: 2 additions & 2 deletions code/Modifier/UnderscoreSegmentFieldModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) ?? '');
}
}
2 changes: 1 addition & 1 deletion code/Task/UserFormsColumnCleanTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function run($request)
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);
Expand Down
Loading