From 8f778d65ba7495d5b613dbcea418049f0e6f8767 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 14:53:48 +1000
Subject: [PATCH 01/41] Add composer requirements, configuration and workflow
for automated updates via GH actions
---
.github/workflows/ci.yml | 15 +++++++++++++++
.gitignore | 5 +++--
.php-cs-fixer.dist.php | 21 ---------------------
composer.json | 28 +++++++++++++++++++++++-----
4 files changed, 41 insertions(+), 28 deletions(-)
create mode 100644 .github/workflows/ci.yml
delete mode 100644 .php-cs-fixer.dist.php
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..a7e347e
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,15 @@
+name: CI
+
+on:
+ pull_request: null
+
+jobs:
+ Bundle:
+ name: 'Automated fixes'
+ uses: nswdpc/ci-files/.github/workflows/bundle.yml@main
+ secrets: inherit
+ PHPStan:
+ name: 'PHPStan (analyse)'
+ uses: nswdpc/ci-files/.github/workflows/phpstan.yml@main
+ secrets: inherit
+ needs: Bundle
diff --git a/.gitignore b/.gitignore
index 7dba068..62e4929 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,5 +2,6 @@
/vendor/
.DS_Store
/.php-cs-fixer.cache
-/codeception.yml
-/tests/codeception/tests/_output/
+/public/
+/composer.lock
+node_modules
diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php
deleted file mode 100644
index f9b7107..0000000
--- a/.php-cs-fixer.dist.php
+++ /dev/null
@@ -1,21 +0,0 @@
-in(__DIR__);
-
-$config = new PhpCsFixer\Config();
-return $config->setRules([
- '@PSR2' => true,
- 'array_indentation' => true,
- 'array_syntax' => ['syntax' => 'short'],
- 'blank_line_after_namespace' => true,
- 'blank_line_after_opening_tag' => true,
- 'full_opening_tag' => true,
- 'no_closing_tag' => true,
- ])
- ->setIndent(" ")
- ->setFinder($finder);
diff --git a/composer.json b/composer.json
index d732728..8186e8a 100644
--- a/composer.json
+++ b/composer.json
@@ -31,9 +31,12 @@
"client/static"
]
},
- "support": {
- "key" : "value"
- },
+ "repositories": [
+ {
+ "type": "git",
+ "url": "https://github.com/nswdpc/ci-files.git"
+ }
+ ],
"require": {
"dnadesign/silverstripe-elemental": "^5",
"silverstripe/framework" : "^5",
@@ -43,9 +46,14 @@
"symbiote/silverstripe-multivaluefield" : "^6"
},
"require-dev": {
- "phpunit/phpunit": "^9.5",
+ "cambis/silverstripe-rector": "^0.5.1",
"friendsofphp/php-cs-fixer": "^3",
- "vlucas/phpdotenv": "^5"
+ "phpstan/phpstan": "^1",
+ "phpunit/phpunit": "^9.5",
+ "rector/rector": "^1",
+ "syntro/silverstripe-phpstan": "^5",
+ "vlucas/phpdotenv": "^5",
+ "nswdpc/ci-files": "*"
},
"autoload": {
"psr-4": {
@@ -60,5 +68,15 @@
"NSWDPC\\Chimple\\Traits\\": "src/Traits/",
"NSWDPC\\Chimple\\Tests\\": "tests/"
}
+ },
+ "prefer-stable": true,
+ "minimum-stability": "dev",
+ "config": {
+ "allow-plugins": {
+ "composer/installers": true,
+ "silverstripe/recipe-plugin": true,
+ "silverstripe/vendor-plugin": true,
+ "phpstan/extension-installer": true
+ }
}
}
From 9c098d01868ebbb2dd5ebb764ff9810432a52d72 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 15:28:09 +1000
Subject: [PATCH 02/41] (ci) remove secrets: inherit config
---
.github/workflows/ci.yml | 2 --
1 file changed, 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a7e347e..74b52b4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -7,9 +7,7 @@ jobs:
Bundle:
name: 'Automated fixes'
uses: nswdpc/ci-files/.github/workflows/bundle.yml@main
- secrets: inherit
PHPStan:
name: 'PHPStan (analyse)'
uses: nswdpc/ci-files/.github/workflows/phpstan.yml@main
- secrets: inherit
needs: Bundle
From 53e5d69cebe65ad37668bdbbab738a0964845289 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:30:40 +1000
Subject: [PATCH 03/41] (phpstan) class referenced with incorrect case
---
_config/routes.yml | 2 +-
src/Extensions/DisableSecurityTokenExtension.php | 2 +-
src/Extensions/SiteConfigExtension.php | 6 +++---
src/Models/MailchimpConfig.php | 2 +-
src/Models/MailchimpSubscriber.php | 2 +-
5 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/_config/routes.yml b/_config/routes.yml
index 58ac1dc..6a32c8d 100644
--- a/_config/routes.yml
+++ b/_config/routes.yml
@@ -3,7 +3,7 @@ Name: silverstripe-chimple-routes
After:
- '#coreroutes'
---
-Silverstripe\Control\Director:
+SilverStripe\Control\Director:
rules:
'mc-subscribe/v1': 'NSWDPC\Chimple\Controllers\ChimpleController'
---
diff --git a/src/Extensions/DisableSecurityTokenExtension.php b/src/Extensions/DisableSecurityTokenExtension.php
index 06919c0..54aeb27 100644
--- a/src/Extensions/DisableSecurityTokenExtension.php
+++ b/src/Extensions/DisableSecurityTokenExtension.php
@@ -2,7 +2,7 @@
namespace NSWDPC\Chimple\Extensions;
-use Silverstripe\Core\Extension;
+use SilverStripe\Core\Extension;
/**
* This extension can be applied at the project level in situations where
diff --git a/src/Extensions/SiteConfigExtension.php b/src/Extensions/SiteConfigExtension.php
index e9d1459..d014b12 100644
--- a/src/Extensions/SiteConfigExtension.php
+++ b/src/Extensions/SiteConfigExtension.php
@@ -4,10 +4,10 @@
use NSWDPC\Chimple\Models\MailchimpConfig;
-use Silverstripe\ORM\DataExtension;
+use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms\CheckboxField;
-use Silverstripe\Forms\FieldList;
-use Silverstripe\Forms\DropdownField;
+use SilverStripe\Forms\FieldList;
+use SilverStripe\Forms\DropdownField;
class SiteConfigExtension extends DataExtension
{
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index dbb2e2f..fcae230 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -13,7 +13,7 @@
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
-use Silverstripe\ORM\DataObject;
+use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\Security\PermissionProvider;
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index 42cc371..a12935d 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -324,7 +324,7 @@ public function getCMSFields()
);
// get profile link
- $dc = MailChimpConfig::getDataCentre();
+ $dc = MailchimpConfig::getDataCentre();
if($dc && $this->SubscribedWebId) {
$subscriber_profile_link = "https://{$dc}.admin.mailchimp.com/lists/members/view?id={$this->SubscribedWebId}";
} else {
From e605e47e13e289d8cbc7a2a59882040b1f2394d8 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:31:18 +1000
Subject: [PATCH 04/41] (phpstan) interface referenced with incorrect case
---
tests/TestSubscribeForm.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tests/TestSubscribeForm.php b/tests/TestSubscribeForm.php
index 8bacb3d..76edd78 100644
--- a/tests/TestSubscribeForm.php
+++ b/tests/TestSubscribeForm.php
@@ -3,7 +3,7 @@
namespace NSWDPC\Chimple\Tests;
use NSWDPC\Chimple\Forms\SubscribeForm;
-use SilverStripe\Dev\Testonly;
+use SilverStripe\Dev\TestOnly;
/**
* Test subscribe form handling
From 102f53bc6ccc763f9ad3d65e39f06c78c7aaf3bd Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:33:35 +1000
Subject: [PATCH 05/41] (phpstan) return can be null
---
src/Controllers/ChimpleController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index ae59087..7d08ec8 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -146,7 +146,7 @@ public function getSubscriptionForm($useXhr = false) : ?SubscribeForm {
* Return a subscription form if it is enabled
* @link MailchimpConfig::SubscribeForm
*/
- public function XhrSubscribeForm() : XhrSubscribeForm
+ public function XhrSubscribeForm() : ?XhrSubscribeForm
{
$enabled = MailchimpConfig::isEnabled();
From 056c31b2e42b4606e999f85ac5440d81fc7efcd0 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:38:36 +1000
Subject: [PATCH 06/41] (phpstan) fix missing class UploadField via requirement
---
composer.json | 1 +
1 file changed, 1 insertion(+)
diff --git a/composer.json b/composer.json
index 8186e8a..8bf15d1 100644
--- a/composer.json
+++ b/composer.json
@@ -41,6 +41,7 @@
"dnadesign/silverstripe-elemental": "^5",
"silverstripe/framework" : "^5",
"silverstripe/siteconfig" : "^5",
+ "silverstripe/asset-admin": "^2",
"symbiote/silverstripe-queuedjobs": "^5",
"drewm/mailchimp-api" : "^2.5",
"symbiote/silverstripe-multivaluefield" : "^6"
From 736c7bf96695f6fc2ad0fa073f919f38b6b16329 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:43:17 +1000
Subject: [PATCH 07/41] (phpstan) improvements to subscriber class
---
src/Models/MailchimpSubscriber.php | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index a12935d..165561c 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -61,7 +61,7 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
/**
* Default chr for obfuscation
- * @var array
+ * @var string
*/
private static $obfuscation_chr = "•";
@@ -76,7 +76,7 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
* attempts to update their subscription
* This is a potentially destructive action as it will remove tags added to
* a subscriber via other means
- * @var string
+ * @var bool
*/
private static $remove_subscriber_tags = false;
@@ -817,7 +817,7 @@ protected function modifySubscriberTags() : bool {
* Retrieve all subscribers marked new and attempt to subscribe them
* @return array
*/
- public static function batch_subscribe($limit = 100, $report_only = false)
+ public static function batch_subscribe($limit = 100, $report_only = false) : array
{
$results = [];
try {
@@ -855,7 +855,7 @@ public static function batch_subscribe($limit = 100, $report_only = false)
Logger::log("FAIL: could not batch_subscribe, error=" . $e->getMessage(), 'NOTICE');
}
- return false;
+ return [];
}
public function canView($member = null)
From c47aa923cf39e2aa17db12158098a43bef744e93 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:43:35 +1000
Subject: [PATCH 08/41] (phpstan) add return type, can be null
---
src/Models/MailchimpConfig.php | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index fcae230..129c503 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -366,9 +366,8 @@ public function requireDefaultRecords()
/**
* Use the form provided by the controller
* @param bool $force_xhr whether to submit in place via XHR or not, the default is to let the config decide
- * @return Form
*/
- public function SubscribeForm($force_xhr = null)
+ public function SubscribeForm($force_xhr = null) : ?SubscribeForm
{
// No form available if not enabled
$enabled = self::isEnabled();
From d3e115fa4d43bb4cbbaab29185fdd7d890c91ee9 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:44:33 +1000
Subject: [PATCH 09/41] (phpstan) fix unreachable statement
---
src/Controllers/ChimpleController.php | 3 ---
1 file changed, 3 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 7d08ec8..5682efa 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -70,13 +70,10 @@ public function pageTitle($complete = null)
switch($complete) {
case 'y':
return _t(__CLASS__. '.DEFAULT_TITLE_SUCCESSFUL', 'Thanks for subscribing');
- break;
case 'n':
return _t(__CLASS__. '.DEFAULT_TITLE_NOT_SUCCESSFUL', 'Sorry, there was an error');
- break;
default:
return _t(__CLASS__. '.DEFAULT_TITLE', 'Subscribe');
- break;
}
}
From 129268af267dd058f8d9f008ccec777308013622 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:48:20 +1000
Subject: [PATCH 10/41] (phpstan) method return type
---
src/Controllers/ChimpleController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 5682efa..299b989 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -175,7 +175,7 @@ public function XhrSubscribeForm() : ?XhrSubscribeForm
* Return a subscription form if it is enabled
* @link MailchimpConfig::SubscribeForm
*/
- public function SubscribeForm()
+ public function SubscribeForm() : ?SubscribeForm
{
$enabled = MailchimpConfig::isEnabled();
From 0ef62360312e6a342c2ae90d7722881f2df36285 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:48:42 +1000
Subject: [PATCH 11/41] (phpstan) exception argument ordering fix
---
src/Controllers/ChimpleController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 299b989..d8ef1e7 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -436,7 +436,7 @@ public function subscribe($data = [], Form $form = null)
$sub->Tags = $mc_config->Tags;
$sub_id = $sub->write();
if (!$sub_id) {
- throw new RequestException("502", "Bad Gateway");
+ throw new RequestException("Bad Gateway", 502);
}
}
From 111223db1be7c278a94c11708fbf8c301b6f37f0 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 17:49:06 +1000
Subject: [PATCH 12/41] (phpstan) argument should be a string
---
src/Controllers/ChimpleController.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index d8ef1e7..f2f807c 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -493,7 +493,7 @@ private function xhrError($code = 500, $message = "", $description = "") {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
- $response->addHeader('X-Submission-OK', 0);
+ $response->addHeader('X-Submission-OK', '0');
$response->addHeader('X-Submission-Description', $message);
return $response;
}
@@ -506,7 +506,7 @@ private function xhrSuccess($code = 200, $message = "", $description = "") {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
- $response->addHeader('X-Submission-OK', 1);
+ $response->addHeader('X-Submission-OK', '1');
$response->addHeader('X-Submission-Description', $description);
return $response;
}
From 2d95d3b2f57708eafb4adeb4e68f624d4761d3f5 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:08:02 +1000
Subject: [PATCH 13/41] (phpstan) add missing class usage
---
src/Models/MailchimpConfig.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index 129c503..f439a6c 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -3,6 +3,7 @@
namespace NSWDPC\Chimple\Models;
use NSWDPC\Chimple\Controllers\ChimpleController;
+use NSWDPC\Chimple\Forms\SubscribeForm;
use NSWDPC\Chimple\Services\Logger;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Config\Config;
From 6ea938706d5320fb1cc20115b0e20fff7ac82e70 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:08:12 +1000
Subject: [PATCH 14/41] (phpstan) add type hint
---
src/Models/Elements/ElementChimpleSubscribe.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/Models/Elements/ElementChimpleSubscribe.php b/src/Models/Elements/ElementChimpleSubscribe.php
index 0c8c4e3..5cd5426 100644
--- a/src/Models/Elements/ElementChimpleSubscribe.php
+++ b/src/Models/Elements/ElementChimpleSubscribe.php
@@ -3,6 +3,7 @@
namespace NSWDPC\Chimple\Models\Elements;
use DNADesign\Elemental\Models\BaseElement;
+use NSWDPC\Chimple\Forms\SubscribeForm;
use NSWDPC\Chimple\Models\MailchimpConfig;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Assets\Image;
@@ -146,9 +147,8 @@ public function getCMSFields()
/**
* Provide $SubscribeForm for template
* When called in the context of the administration area, return null
- * @return Form|null
*/
- public function getSubscribeForm() {
+ public function getSubscribeForm(): ?SubscribeForm {
if(Controller::curr() instanceof LeftAndMain) {
return null;
From 211ef8a7a17b1a721f80697e3d61cbed15dff5c5 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:12:13 +1000
Subject: [PATCH 15/41] (phpstan) replace strpos with simpler str_contains
---
tests/ChimpleConfigTest.php | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/tests/ChimpleConfigTest.php b/tests/ChimpleConfigTest.php
index 25a9305..b24f45c 100644
--- a/tests/ChimpleConfigTest.php
+++ b/tests/ChimpleConfigTest.php
@@ -173,21 +173,21 @@ public function testSubscribeFormTemplateVariable() {
// Use config value
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") === false, "Attribute is not in template");
+ $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") !== false, "Attribute is in template");
+ $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
// template override
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '1');
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") !== false, "Attribute is in template");
+ $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '0');
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") === false, "Attribute is not in template");
+ $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
}
public function testGlobalSubscribeFormTemplateVariable() {
From 5a90595897145538b808297b9b70720644eefb63 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:20:23 +1000
Subject: [PATCH 16/41] (phpstan) replace strpos with simpler str_contains
---
tests/ChimpleConfigTest.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/tests/ChimpleConfigTest.php b/tests/ChimpleConfigTest.php
index b24f45c..e279202 100644
--- a/tests/ChimpleConfigTest.php
+++ b/tests/ChimpleConfigTest.php
@@ -133,7 +133,7 @@ public function testConfiguration()
$this->assertTrue( $static_form instanceof DBHTMLText, "Static form for code {$code_value} was not returned");
$needle = " value=\"{$code_value}\" ";
- $this->assertTrue( strpos($static_form->forTemplate(), $needle) !== false, "Missing {$code_value} input from form HTML");
+ $this->assertTrue( str_contains($static_form->forTemplate(), $needle), "Missing {$code_value} input from form HTML");
}
@@ -196,10 +196,10 @@ public function testGlobalSubscribeFormTemplateVariable() {
$config->write();
// Use config value
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") === false, "Attribute is not in template");
+ $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue( strpos($template, "data-xhr=\"1\"") !== false, "Attribute is in template");
+ $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
}
}
From bb63a8cc5d04e662921263560e80b33454aa8041 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:20:34 +1000
Subject: [PATCH 17/41] (phpstan) remove comments
---
src/Controllers/ChimpleController.php | 2 --
1 file changed, 2 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index f2f807c..28396ed 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -141,7 +141,6 @@ public function getSubscriptionForm($useXhr = false) : ?SubscribeForm {
/**
* Return a subscription form if it is enabled
- * @link MailchimpConfig::SubscribeForm
*/
public function XhrSubscribeForm() : ?XhrSubscribeForm
{
@@ -173,7 +172,6 @@ public function XhrSubscribeForm() : ?XhrSubscribeForm
/**
* Return a subscription form if it is enabled
- * @link MailchimpConfig::SubscribeForm
*/
public function SubscribeForm() : ?SubscribeForm
{
From bd82c4ecbc7cd86ba9b2c605771085547e8b8ea4 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:22:55 +1000
Subject: [PATCH 18/41] (phpstan) add union return type
---
src/Controllers/ChimpleController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 28396ed..0e1beb3 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -130,7 +130,7 @@ public function getFormNameSuffix() : string {
/**
* Get a subscription form based on parameters
*/
- public function getSubscriptionForm($useXhr = false) : ?SubscribeForm {
+ public function getSubscriptionForm($useXhr = false) : SubscribeForm|XhrSubscribeForm|null {
if($useXhr) {
$form = $this->XhrSubscribeForm();
} else {
From 59fbccabfe9fb4c26131d92103f11d6970f9fc3d Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:34:19 +1000
Subject: [PATCH 19/41] (phpstan) improve message/email/config handling
---
src/Controllers/ChimpleController.php | 24 ++++++++++++------------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 0e1beb3..0c1af12 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -329,13 +329,14 @@ public function subscribe($data = [], Form $form = null)
$response = null;
$code = "";// MailchimpConfig.Code
$list_id = "";
+ $mc_config = null;
+ $error_message = "";
+ $email = $data['Email'] ?? '';
if(!$form) {
throw new RequestException("Forbidden", 403);
}
- $mc_config = null;
-
if(empty($data['code'])) {
// fail with error
$error_message = _t(
@@ -349,7 +350,6 @@ public function subscribe($data = [], Form $form = null)
$code = strip_tags(trim($data['code'] ?: ''));
$error_message = "";
$error_code = 400;// default to invalid data
- $mc_config = null;
}
@@ -363,14 +363,13 @@ public function subscribe($data = [], Form $form = null)
// proceed with Email checking...
if (!$error_message) {
- if (empty($data['Email'])) {
+ if ($email === '') {
// fail with error
$error_message = _t(
__CLASS__ . '.NO_EMAIL_ADDRESS',
"No e-mail address was provided"
);
- }
- if (!Email::is_valid_address($data['Email'])) {
+ } elseif (!Email::is_valid_address($email)) {
$error_message = _t(
__CLASS__ . '.INVALID_EMAIL_ADDRESS',
"Please provide a valid e-mail address, '{email}' is not valid",
@@ -395,8 +394,9 @@ public function subscribe($data = [], Form $form = null)
__CLASS__ . ".GENERIC_ERROR_2",
"Sorry, the sign-up could not be completed"
);
+ } else {
+ $list_id = $mc_config->getMailchimpListId();
}
- $list_id = $mc_config->getMailchimpListId();
}
}
@@ -421,17 +421,17 @@ public function subscribe($data = [], Form $form = null)
])
// for the Email or the MD5 of it
->filterAny([
- 'Email' => $data['Email'],// match on email address provided
- 'SubscribedId' => MailchimpSubscriber::getMailchimpSubscribedId($data['Email'])// OR may not have the email anymore
+ 'Email' => $email,// match on email address provided
+ 'SubscribedId' => MailchimpSubscriber::getMailchimpSubscribedId($email)// OR may not have the email anymore
])->first();
if (empty($sub->ID)) {
$sub = MailchimpSubscriber::create();
- $sub->Name = $data['Name'];
- $sub->Email = $data['Email'];
+ $sub->Name = $data['Name'] ?? '';
+ $sub->Email = $email;
$sub->MailchimpListId = $list_id;//list they are subscribing to
$sub->Status = MailchimpSubscriber::CHIMPLE_STATUS_NEW;
- $sub->Tags = $mc_config->Tags;
+ $sub->Tags = $mc_config ? $mc_config->Tags : null;
$sub_id = $sub->write();
if (!$sub_id) {
throw new RequestException("Bad Gateway", 502);
From 650ff597d7ae2ba42d7d5352e540ef88fab8f86f Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:44:26 +1000
Subject: [PATCH 20/41] (phpstan) add return types
---
src/Models/MailchimpConfig.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index f439a6c..b2431a4 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -173,7 +173,7 @@ public static function getGlobalConfig() {
/**
* If not configured in the database, return the value in yml
*/
- public function getMailchimpListId()
+ public function getMailchimpListId(): ?string
{
$list_id = $this->getField('MailchimpListId');
if (!$list_id) {
@@ -187,7 +187,7 @@ public function HasMailchimpListId()
return $this->getMailchimpListId() != '';
}
- public static function getConfig($id = '', $list_id = '', $code = '')
+ public static function getConfig($id = '', $list_id = '', $code = ''): ?self
{
if ($id) {
return MailchimpConfig::get()->byId($id);
@@ -198,7 +198,7 @@ public static function getConfig($id = '', $list_id = '', $code = '')
if ($code) {
return MailchimpConfig::get()->filter('Code', $code)->first();
}
- return false;
+ return null;
}
/**
From c8894c482bf712460c670ec949cd7a64e5089471 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:45:02 +1000
Subject: [PATCH 21/41] (phpstan) update handling of code and config
---
src/Controllers/ChimpleController.php | 14 +++++---------
1 file changed, 5 insertions(+), 9 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 0c1af12..792f75a 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -327,7 +327,7 @@ public function subscribe($data = [], Form $form = null)
try {
$response = null;
- $code = "";// MailchimpConfig.Code
+ $code = strip_tags(trim($data['code'] ?? ''));// MailchimpConfig.Code
$list_id = "";
$mc_config = null;
$error_message = "";
@@ -337,20 +337,16 @@ public function subscribe($data = [], Form $form = null)
throw new RequestException("Forbidden", 403);
}
- if(empty($data['code'])) {
+ if($code === "") {
// fail with error
$error_message = _t(
__CLASS__ . '.NO_CODE',
"No code was provided"
);
$error_code = 400;// default to invalid data
-
} else {
-
- $code = strip_tags(trim($data['code'] ?: ''));
$error_message = "";
$error_code = 400;// default to invalid data
-
}
$enabled = MailchimpConfig::isEnabled();
@@ -389,13 +385,13 @@ public function subscribe($data = [], Form $form = null)
);
} else {
$mc_config = MailchimpConfig::getConfig('', '', $code);
- if (empty($mc_config->ID)) {
+ if ($mc_config) {
+ $list_id = $mc_config->getMailchimpListId();
+ } else {
$error_message = _t(
__CLASS__ . ".GENERIC_ERROR_2",
"Sorry, the sign-up could not be completed"
);
- } else {
- $list_id = $mc_config->getMailchimpListId();
}
}
}
From 9af709fa7dd53570cbc2fe20e48e39817b2f5ff1 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:49:55 +1000
Subject: [PATCH 22/41] (phpstan) return types
---
src/Extensions/PageExtension.php | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/Extensions/PageExtension.php b/src/Extensions/PageExtension.php
index 40f5463..993eee3 100644
--- a/src/Extensions/PageExtension.php
+++ b/src/Extensions/PageExtension.php
@@ -2,6 +2,7 @@
namespace NSWDPC\Chimple\Extensions;
+use NSWDPC\Chimple\Forms\SubscribeForm;
use NSWDPC\Chimple\Models\MailchimpConfig;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Core\Config\Config;
@@ -13,9 +14,8 @@ class PageExtension extends Extension
/**
* Returns a form for the configuration marked 'IsGlobal'
- * @return Form|null
*/
- public function ChimpleGlobalSubscribeForm() {
+ public function ChimpleGlobalSubscribeForm(): ?SubscribeForm {
$config = MailchimpConfig::getGlobalConfig();
if ($config) {
return $config->SubscribeForm();
@@ -25,10 +25,9 @@ public function ChimpleGlobalSubscribeForm() {
/**
* Returns a form based on a config code
- * @return Form|null
* @param string $config_code a MailchimpConfig.Code value (not an audience ID)
*/
- public function ChimpleSubscribeForm($config_code)
+ public function ChimpleSubscribeForm(string $config_code): ?SubscribeForm
{
$config = MailchimpConfig::getConfig('', '', $config_code);
if($config) {
From e255ffb413da7f804c568651f1dc305e18cf63a6 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Wed, 7 Aug 2024 18:55:54 +1000
Subject: [PATCH 23/41] (phpstan) return types update
---
src/Controllers/ChimpleController.php | 8 ++------
src/Models/MailchimpConfig.php | 16 +++++-----------
src/Models/MailchimpSubscriber.php | 25 ++++++++-----------------
3 files changed, 15 insertions(+), 34 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 792f75a..3c34d9c 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -253,7 +253,6 @@ protected function getActions() : FieldList {
/**
* Return the default validator for the form.
- * @returns Validator|null
*/
protected function getValidator() : ?Validator {
return RequiredFields::create(['Name','Email']);
@@ -263,7 +262,6 @@ protected function getValidator() : ?Validator {
* Returns the validation callback upon errors
* A response is returned only upon errors in XHR submissions
* See FormRequestHandler::getValidationErrorResponse();
- * @return callable
*/
protected function getCallbackForXhrValidation() : callable {
return function(ValidationResult $result) {
@@ -481,9 +479,8 @@ public function subscribe($data = [], Form $form = null)
/**
* Return error response for XHR
- * @return HTTPResponse
*/
- private function xhrError($code = 500, $message = "", $description = "") {
+ private function xhrError($code = 500, $message = "", $description = ""): HTTPResponse {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
@@ -494,9 +491,8 @@ private function xhrError($code = 500, $message = "", $description = "") {
/**
* Return success response for XHR
- * @return HTTPResponse
*/
- private function xhrSuccess($code = 200, $message = "", $description = "") {
+ private function xhrSuccess($code = 200, $message = "", $description = ""): HTTPResponse {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index b2431a4..23692fc 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -121,7 +121,6 @@ public static function getApiKey()
/**
* Returns the data centre (dc) component based on the API key e.g us2
- * @return string
*/
public static function getDataCentre() : string {
$dc = '';
@@ -329,9 +328,8 @@ public function getCMSFields()
/**
* Return signup link
- * @return string
*/
- public function MailchimpLink()
+ public function MailchimpLink() : string
{
return singleton(ChimpleController::class)->Link();
}
@@ -405,9 +403,8 @@ public function SubscribeForm($force_xhr = null) : ?SubscribeForm
/**
* Return alerts for the form
- * @return string
*/
- public function Alerts()
+ public function Alerts(): string
{
return '
'
. _t(__CLASS__ . '.SUBSCRIBE_SUCCESS', htmlspecialchars($this->config()->get('success_message')))
@@ -462,9 +459,8 @@ public function providePermissions()
/**
* Render this record using a template
- * @return DBHTMLText|null
*/
- public function forTemplate($force_xhr = null)
+ public function forTemplate($force_xhr = null) : ?DBHTMLText
{
$form = $this->SubscribeForm($force_xhr);
if($form) {
@@ -479,9 +475,8 @@ public function forTemplate($force_xhr = null)
* The 2nd parameter is a 1 or 0 representing whether to handle the submission via XHR
* This is called from a template calling $ChimpleSubscribeForm('code'[,0|1])
* @param array $args
- * @return DBHTMLText|null
*/
- public static function get_chimple_subscribe_form(...$args)
+ public static function get_chimple_subscribe_form(...$args) : ?DBHTMLText
{
$code = isset($args[0]) ? $args[0] : '';
if ($code) {
@@ -507,9 +502,8 @@ public static function get_chimple_subscribe_form(...$args)
/**
* Get the subscribe form for the current global config
* This is called from a template calling $ChimpleSubscribeForm('code')
- * @return DBHTMLText|null
*/
- public static function get_chimple_global_subscribe_form()
+ public static function get_chimple_global_subscribe_form() : ?DBHTMLText
{
$config = self::getGlobalConfig();
if ($config) {
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index 165561c..ad0f3d9 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -416,7 +416,6 @@ public function getSurnameFromName()
/**
* Get the API client
- * @return MailchimpApiClient
*/
public static function api() : MailchimpApiClient {
// already set up..
@@ -452,9 +451,8 @@ public function getMailchimpListId()
/**
* Applies merge fields prior to subscription attempt
- * @return array
*/
- protected function applyMergeFields() {
+ protected function applyMergeFields(): array {
$merge_fields = [];
// get subscriber meta data
@@ -498,7 +496,6 @@ protected function applyMergeFields() {
/**
* Get the default subscription record data for adding/updating member in list
- * @return array
*/
public function getSubscribeRecord() : array {
// merge fields to send
@@ -530,10 +527,9 @@ public function getSubscriberTags() {
/**
* Called after a successful subscription, obfuscates email, name and surname
- * @return void
*/
private function obfuscate() {
- $obfuscate = function($in) {
+ $obfuscate = function(string $in) : string {
$length = strlen($in);
if($length == 0) {
return "";
@@ -550,16 +546,15 @@ private function obfuscate() {
$replaced = substr_replace($in, str_repeat($chr, $sub_length), 1, $sub_length);
return $replaced;
};
- $this->Email = $obfuscate($this->Email);
- $this->Name = $obfuscate($this->Name);
- $this->Surname = $obfuscate($this->Surname);
+ $this->Email = $obfuscate($this->Email ?? '');
+ $this->Name = $obfuscate($this->Name ?? '');
+ $this->Surname = $obfuscate($this->Surname ?? '');
}
/**
* Get the hash that is used as the MC subscribed Id value
- * @return string
*/
- public static function getMailchimpSubscribedId($email) {
+ public static function getMailchimpSubscribedId($email): string {
if(!is_string($email) || !$email) {
return '';
} else {
@@ -572,9 +567,8 @@ public static function getMailchimpSubscribedId($email) {
* @param string $list_id the Audience ID
* @param string $email an email address, this is hashed using the MC hashing strategy
* @param string $api_key @deprecated
- * @return boolean|array
*/
- public static function checkExistsInList(string $list_id, string $email, string $api_key = '') {
+ public static function checkExistsInList(string $list_id, string $email, string $api_key = '') : array|false {
// sanity check on input
if(!$email) {
@@ -612,9 +606,8 @@ public static function checkExistsInList(string $list_id, string $email, string
/**
* Subscribe *this* particular record
- * @return bool
*/
- public function subscribe()
+ public function subscribe() : bool
{
try {
@@ -700,7 +693,6 @@ public function subscribe()
* Return all current tags for a subscriber and handle pagination at the time of the API call
* @param bool $force whether to get the tags from the remote or use previously retrieved tags
* @param int $count the number of records to return per request
- * @return array an array of values, each value is a string tag
*/
private function getCurrentSubscriberTags(bool $force = false, int $count = 10) : array {
@@ -815,7 +807,6 @@ protected function modifySubscriberTags() : bool {
/**
* Batch subscribe via API - hit from MailchimpSubscribeJob
* Retrieve all subscribers marked new and attempt to subscribe them
- * @return array
*/
public static function batch_subscribe($limit = 100, $report_only = false) : array
{
From b3fd0bf5ea304aeab68a210d26943bd03a6e908e Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 12:26:50 +1000
Subject: [PATCH 24/41] (phpstan) handle type checking requirement enforcing
class of form to return
---
src/Controllers/ChimpleController.php | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 3c34d9c..068c873 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -167,7 +167,8 @@ public function XhrSubscribeForm() : ?XhrSubscribeForm
// this form doesn't need to retain state
$form->clearMessage();
- return $form;
+ // phpstan return type checking requirement
+ return $form instanceof XhrSubscribeForm ? $form : null;
}
/**
From acb7167f3b8a83af8f0c74fb4f30192691acd90a Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Thu, 8 Aug 2024 02:27:28 +0000
Subject: [PATCH 25/41] [php-cs-fixer] Automated updates generated by
php-cs-fixer configuration
---
src/Controllers/ChimpleController.php | 56 ++++++++-----
src/Exceptions/RequestException.php | 4 +-
.../DisableSecurityTokenExtension.php | 3 +-
src/Extensions/PageExtension.php | 4 +-
src/Forms/SubscribeForm.php | 4 +-
src/Forms/XhrSubscribeForm.php | 4 +-
src/Jobs/MailchimpCleanupJob.php | 4 +-
.../Elements/ElementChimpleSubscribe.php | 11 +--
src/Models/MailchimpConfig.php | 69 ++++++++-------
src/Models/MailchimpSubscriber.php | 83 +++++++++++--------
src/Traits/SubscriptionForm.php | 7 +-
tests/ChimpleConfigTest.php | 56 +++++++------
tests/ChimpleFunctionalTest.php | 11 +--
tests/ChimpleSubscriberTest.php | 17 ++--
tests/TestSubscribeForm.php | 7 +-
15 files changed, 190 insertions(+), 150 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 068c873..caa94c6 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -31,7 +31,6 @@
*/
class ChimpleController extends PageController
{
-
/**
* @var string
*/
@@ -109,7 +108,8 @@ public function Form()
/**
* Set a suffix form the form name
*/
- public function setFormNameSuffix(string $suffix = '') : self {
+ public function setFormNameSuffix(string $suffix = ''): self
+ {
$suffix = trim($suffix);
$this->formNameSuffix = $suffix;
return $this;
@@ -118,7 +118,8 @@ public function setFormNameSuffix(string $suffix = '') : self {
/**
* Return a suffix to use with the form name
*/
- public function getFormNameSuffix() : string {
+ public function getFormNameSuffix(): string
+ {
if($this->formNameSuffix) {
$suffix = "_{$this->formNameSuffix}";
} else {
@@ -130,7 +131,8 @@ public function getFormNameSuffix() : string {
/**
* Get a subscription form based on parameters
*/
- public function getSubscriptionForm($useXhr = false) : SubscribeForm|XhrSubscribeForm|null {
+ public function getSubscriptionForm($useXhr = false): SubscribeForm|XhrSubscribeForm|null
+ {
if($useXhr) {
$form = $this->XhrSubscribeForm();
} else {
@@ -142,7 +144,7 @@ public function getSubscriptionForm($useXhr = false) : SubscribeForm|XhrSubscrib
/**
* Return a subscription form if it is enabled
*/
- public function XhrSubscribeForm() : ?XhrSubscribeForm
+ public function XhrSubscribeForm(): ?XhrSubscribeForm
{
$enabled = MailchimpConfig::isEnabled();
@@ -159,7 +161,7 @@ public function XhrSubscribeForm() : ?XhrSubscribeForm
);
$form = $this->configureForm($form);
- $form->setFormAction( $this->Link('XhrSubscribeForm') );
+ $form->setFormAction($this->Link('XhrSubscribeForm'));
// Set a validation response callback handling for XHR form submissions
$form->setValidationResponseCallback($this->getCallbackForXhrValidation());
@@ -174,7 +176,7 @@ public function XhrSubscribeForm() : ?XhrSubscribeForm
/**
* Return a subscription form if it is enabled
*/
- public function SubscribeForm() : ?SubscribeForm
+ public function SubscribeForm(): ?SubscribeForm
{
$enabled = MailchimpConfig::isEnabled();
@@ -191,7 +193,7 @@ public function SubscribeForm() : ?SubscribeForm
);
$form = $this->configureForm($form);
- $form->setFormAction( $this->Link('SubscribeForm') );
+ $form->setFormAction($this->Link('SubscribeForm'));
// Handle error validation with custom callback
$form->setValidationResponseCallback($this->getCallbackForValidation($form));
@@ -202,7 +204,8 @@ public function SubscribeForm() : ?SubscribeForm
/**
* Apply common configuration to a subscription form
*/
- protected function configureForm(SubscribeForm $form) : SubscribeForm {
+ protected function configureForm(SubscribeForm $form): SubscribeForm
+ {
// Form JS, incl XHR handling
Requirements::javascript(
'nswdpc/silverstripe-chimple:client/static/js/chimple.js'
@@ -224,7 +227,8 @@ protected function configureForm(SubscribeForm $form) : SubscribeForm {
/**
* Get fields for the form
*/
- protected function getFields() : FieldList {
+ protected function getFields(): FieldList
+ {
$fields = FieldList::create(
$name = TextField::create('Name', _t(__CLASS__. '.NAME', 'Name'))
->setAttribute('placeholder', _t(__CLASS__. '.YOUR_NAME', 'Your name'))
@@ -241,7 +245,8 @@ protected function getFields() : FieldList {
/**
* Get actions for the form
*/
- protected function getActions() : FieldList {
+ protected function getActions(): FieldList
+ {
$actions = FieldList::create(
FormAction::create(
'subscribe',
@@ -255,7 +260,8 @@ protected function getActions() : FieldList {
/**
* Return the default validator for the form.
*/
- protected function getValidator() : ?Validator {
+ protected function getValidator(): ?Validator
+ {
return RequiredFields::create(['Name','Email']);
}
@@ -264,8 +270,9 @@ protected function getValidator() : ?Validator {
* A response is returned only upon errors in XHR submissions
* See FormRequestHandler::getValidationErrorResponse();
*/
- protected function getCallbackForXhrValidation() : callable {
- return function(ValidationResult $result) {
+ protected function getCallbackForXhrValidation(): callable
+ {
+ return function (ValidationResult $result) {
// Fail, using the first message returned from the validation result
$messages = $result->getMessages();
$message = (!empty($messages[0]['message']) ? $messages[0]['message'] : '');
@@ -276,8 +283,9 @@ protected function getCallbackForXhrValidation() : callable {
/**
* Callback validator for SubscribeForm, avoid redirectBack()
*/
- protected function getCallbackForValidation(SubscribeForm $form) : callable {
- return function(ValidationResult $result) use ($form) {
+ protected function getCallbackForValidation(SubscribeForm $form): callable
+ {
+ return function (ValidationResult $result) use ($form) {
// Prior to redirection, persist this result in session to re-display on redirect
$form->setSessionValidationResult($result);
$form->setSessionData($form->getData());
@@ -293,10 +301,11 @@ protected function getCallbackForValidation(SubscribeForm $form) : callable {
/**
* Handle errors, based on the request type
*/
- private function handleError($code, $error_message, Form $form = null) {
+ private function handleError($code, $error_message, Form $form = null)
+ {
if($this->request->isAjax()) {
return $this->xhrError($code, $error_message);
- } else if($form) {
+ } elseif($form) {
// set session error on the form
$form->sessionError($error_message, ValidationResult::TYPE_ERROR);
}
@@ -306,11 +315,12 @@ private function handleError($code, $error_message, Form $form = null) {
/**
* Handle successful submissions, based on the request type
*/
- private function handleSuccess($code, $message, Form $form = null) {
+ private function handleSuccess($code, $message, Form $form = null)
+ {
$success_message = Config::inst()->get(MailchimpConfig::class, 'success_message');
if($this->request->isAjax()) {
return $this->xhrSuccess($code, $message, $success_message);
- } else if($form) {
+ } elseif($form) {
// set session message on the form
$form->sessionMessage($success_message, ValidationResult::TYPE_GOOD);
}
@@ -481,7 +491,8 @@ public function subscribe($data = [], Form $form = null)
/**
* Return error response for XHR
*/
- private function xhrError($code = 500, $message = "", $description = ""): HTTPResponse {
+ private function xhrError($code = 500, $message = "", $description = ""): HTTPResponse
+ {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
@@ -493,7 +504,8 @@ private function xhrError($code = 500, $message = "", $description = ""): HTTPRe
/**
* Return success response for XHR
*/
- private function xhrSuccess($code = 200, $message = "", $description = ""): HTTPResponse {
+ private function xhrSuccess($code = 200, $message = "", $description = ""): HTTPResponse
+ {
$response = new HTTPResponse();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
diff --git a/src/Exceptions/RequestException.php b/src/Exceptions/RequestException.php
index 8c43bff..7df4327 100644
--- a/src/Exceptions/RequestException.php
+++ b/src/Exceptions/RequestException.php
@@ -6,4 +6,6 @@
* An exception thrown when an incoming subscription request is determined to be
* invalid
*/
-class RequestException extends \Exception {}
+class RequestException extends \Exception
+{
+}
diff --git a/src/Extensions/DisableSecurityTokenExtension.php b/src/Extensions/DisableSecurityTokenExtension.php
index 54aeb27..2321f1b 100644
--- a/src/Extensions/DisableSecurityTokenExtension.php
+++ b/src/Extensions/DisableSecurityTokenExtension.php
@@ -12,7 +12,8 @@
*/
class DisableSecurityTokenExtension extends Extension
{
- public function updateChimpleSubscribeForm() {
+ public function updateChimpleSubscribeForm()
+ {
$this->owner->disableSecurityToken();
}
}
diff --git a/src/Extensions/PageExtension.php b/src/Extensions/PageExtension.php
index 993eee3..0384509 100644
--- a/src/Extensions/PageExtension.php
+++ b/src/Extensions/PageExtension.php
@@ -11,11 +11,11 @@
class PageExtension extends Extension
{
-
/**
* Returns a form for the configuration marked 'IsGlobal'
*/
- public function ChimpleGlobalSubscribeForm(): ?SubscribeForm {
+ public function ChimpleGlobalSubscribeForm(): ?SubscribeForm
+ {
$config = MailchimpConfig::getGlobalConfig();
if ($config) {
return $config->SubscribeForm();
diff --git a/src/Forms/SubscribeForm.php b/src/Forms/SubscribeForm.php
index 48c64b6..777fa21 100644
--- a/src/Forms/SubscribeForm.php
+++ b/src/Forms/SubscribeForm.php
@@ -10,8 +10,8 @@
* Subscription form subclass of {@link SilverStripe\Forms\Form}
* Allows overrides of default form behaviour
*/
-class SubscribeForm extends Form {
-
+class SubscribeForm extends Form
+{
use SubscriptionForm;
}
diff --git a/src/Forms/XhrSubscribeForm.php b/src/Forms/XhrSubscribeForm.php
index d7e196a..d0a718c 100644
--- a/src/Forms/XhrSubscribeForm.php
+++ b/src/Forms/XhrSubscribeForm.php
@@ -13,8 +13,8 @@
* Subscription form subclass to handle submissions via XHR
* Allows overrides of default form behaviour
*/
-class XhrSubscribeForm extends SubscribeForm {
-
+class XhrSubscribeForm extends SubscribeForm
+{
/**
* Set to true if forms of this class will appear on a publicly cacheable page
* @var bool
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 576d3a1..61f79ea 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -97,8 +97,8 @@ private function processSubscriptions()
$fail_datetime = new DateTime();
$fail_datetime->modify('-7 days');
$failed = MailchimpSubscriber::get()->filter([
- 'Status' => MailchimpSubscriber::CHIMPLE_STATUS_FAIL,
- 'Created:LessThan' => $fail_datetime->format('Y-m-d H:i:s')
+ 'Status' => MailchimpSubscriber::CHIMPLE_STATUS_FAIL,
+ 'Created:LessThan' => $fail_datetime->format('Y-m-d H:i:s')
]);
if ($this->report_only) {
diff --git a/src/Models/Elements/ElementChimpleSubscribe.php b/src/Models/Elements/ElementChimpleSubscribe.php
index 5cd5426..17fbe4b 100644
--- a/src/Models/Elements/ElementChimpleSubscribe.php
+++ b/src/Models/Elements/ElementChimpleSubscribe.php
@@ -24,7 +24,6 @@
*/
class ElementChimpleSubscribe extends BaseElement
{
-
private static $table_name = 'ElementChimpleSubscribe';
private static $singular_name = 'Mailchimp subscribe';
@@ -86,14 +85,15 @@ public function getCMSFields()
]);
$fields->addFieldsToTab(
- 'Root.Main', [
+ 'Root.Main',
+ [
DropdownField::create(
'MailchimpConfigID',
_t(
__CLASS__ . '.SELECT_CONFIGURATION',
'Select the list configuration to use for this subscription form'
),
- MailchimpConfig::get()->sort('Title ASC')->map('ID','TitleWithDetails')
+ MailchimpConfig::get()->sort('Title ASC')->map('ID', 'TitleWithDetails')
)->setEmptyString(''),
CheckboxField::create(
'UseXHR',
@@ -148,7 +148,8 @@ public function getCMSFields()
* Provide $SubscribeForm for template
* When called in the context of the administration area, return null
*/
- public function getSubscribeForm(): ?SubscribeForm {
+ public function getSubscribeForm(): ?SubscribeForm
+ {
if(Controller::curr() instanceof LeftAndMain) {
return null;
@@ -156,7 +157,7 @@ public function getSubscribeForm(): ?SubscribeForm {
if($config = $this->MailchimpConfig()) {
// render the form with this element's XHR setting overriding the config being used
- $form = $config->SubscribeForm( $this->UseXHR == 1 );
+ $form = $config->SubscribeForm($this->UseXHR == 1);
return $form;
}
return null;
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index 23692fc..7c0926d 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -31,7 +31,6 @@
*/
class MailchimpConfig extends DataObject implements TemplateGlobalProvider, PermissionProvider
{
-
private static $list_id = "";// default list (audience) ID
private static $api_key = "";// API key provided by Mailchimp
@@ -100,11 +99,13 @@ class MailchimpConfig extends DataObject implements TemplateGlobalProvider, Perm
'UseXHR' => 1
];
- public function TitleCode() {
+ public function TitleCode()
+ {
return "{$this->Title} ({$this->Code})";
}
- public static function isEnabled() {
+ public static function isEnabled()
+ {
$site_config = SiteConfig::current_site_config();
return $site_config->MailchimpEnabled == 1;
}
@@ -122,7 +123,8 @@ public static function getApiKey()
/**
* Returns the data centre (dc) component based on the API key e.g us2
*/
- public static function getDataCentre() : string {
+ public static function getDataCentre(): string
+ {
$dc = '';
$key = self::getApiKey();
$parts = [];
@@ -132,11 +134,13 @@ public static function getDataCentre() : string {
return !empty($parts[1]) ? $parts[1] : '';
}
- public function TitleWithCode() {
+ public function TitleWithCode()
+ {
return $this->Title . " - (code {$this->Code})";
}
- public function TitleWithDetails() {
+ public function TitleWithDetails()
+ {
$title = $this->Title;
$list_id = $this->getMailchimpListId();
$title .= " (list {$list_id})";
@@ -165,7 +169,8 @@ public function onBeforeWrite()
/**
* Return the current global config
*/
- public static function getGlobalConfig() {
+ public static function getGlobalConfig()
+ {
return MailchimpConfig::get()->filter(['IsGlobal' => 1])->first();
}
@@ -267,7 +272,7 @@ public function getCMSFields()
. _t(
__CLASS__. '.CONFIG_IS_GLOBAL',
'This configuration is the default for this website'
- )
+ )
. ''
),
'Title'
@@ -298,22 +303,24 @@ public function getCMSFields()
);
$fields->addFieldsToTab(
- 'Root.Main', [
- HTMLEditorField::create(
- 'BeforeFormContent',
- _t(
- __CLASS__ . '.BEFORE_CONTENT',
- 'Content to show before form'
- )
- )->setRows(6),
- HTMLEditorField::create(
- 'AfterFormContent',
- _t(
- __CLASS__ . '.AFTER_CONTENT',
- 'Content to show after form'
- )
- )->setRows(6)
- ]);
+ 'Root.Main',
+ [
+ HTMLEditorField::create(
+ 'BeforeFormContent',
+ _t(
+ __CLASS__ . '.BEFORE_CONTENT',
+ 'Content to show before form'
+ )
+ )->setRows(6),
+ HTMLEditorField::create(
+ 'AfterFormContent',
+ _t(
+ __CLASS__ . '.AFTER_CONTENT',
+ 'Content to show after form'
+ )
+ )->setRows(6)
+ ]
+ );
if($heading = $fields->dataFieldByName('Heading')) {
$heading->setDescription(_t(
@@ -329,7 +336,7 @@ public function getCMSFields()
/**
* Return signup link
*/
- public function MailchimpLink() : string
+ public function MailchimpLink(): string
{
return singleton(ChimpleController::class)->Link();
}
@@ -366,7 +373,7 @@ public function requireDefaultRecords()
* Use the form provided by the controller
* @param bool $force_xhr whether to submit in place via XHR or not, the default is to let the config decide
*/
- public function SubscribeForm($force_xhr = null) : ?SubscribeForm
+ public function SubscribeForm($force_xhr = null): ?SubscribeForm
{
// No form available if not enabled
$enabled = self::isEnabled();
@@ -460,11 +467,11 @@ public function providePermissions()
/**
* Render this record using a template
*/
- public function forTemplate($force_xhr = null) : ?DBHTMLText
+ public function forTemplate($force_xhr = null): ?DBHTMLText
{
$form = $this->SubscribeForm($force_xhr);
if($form) {
- return $this->customise(['Form'=>$form])->renderWith( self::class );
+ return $this->customise(['Form' => $form])->renderWith(self::class);
}
return null;
}
@@ -476,7 +483,7 @@ public function forTemplate($force_xhr = null) : ?DBHTMLText
* This is called from a template calling $ChimpleSubscribeForm('code'[,0|1])
* @param array $args
*/
- public static function get_chimple_subscribe_form(...$args) : ?DBHTMLText
+ public static function get_chimple_subscribe_form(...$args): ?DBHTMLText
{
$code = isset($args[0]) ? $args[0] : '';
if ($code) {
@@ -488,7 +495,7 @@ public static function get_chimple_subscribe_form(...$args) : ?DBHTMLText
if($args[1] === '0') {
// string '0' passed in as an arg in the template
$force_xhr = false;
- } else if($args[1] === '1') {
+ } elseif($args[1] === '1') {
// string '1' passed in as an arg in the template
$force_xhr = true;
}
@@ -503,7 +510,7 @@ public static function get_chimple_subscribe_form(...$args) : ?DBHTMLText
* Get the subscribe form for the current global config
* This is called from a template calling $ChimpleSubscribeForm('code')
*/
- public static function get_chimple_global_subscribe_form() : ?DBHTMLText
+ public static function get_chimple_global_subscribe_form(): ?DBHTMLText
{
$config = self::getGlobalConfig();
if ($config) {
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index ad0f3d9..e3bdeaf 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -18,23 +18,23 @@
class MailchimpSubscriber extends DataObject implements PermissionProvider
{
- const CHIMPLE_STATUS_UNKNOWN = '';
- const CHIMPLE_STATUS_NEW = 'NEW';
- const CHIMPLE_STATUS_PROCESSING = 'PROCESSING';
- const CHIMPLE_STATUS_BATCHED = 'BATCHED';
- const CHIMPLE_STATUS_SUCCESS = 'SUCCESS';
- const CHIMPLE_STATUS_FAIL = 'FAIL';
+ public const CHIMPLE_STATUS_UNKNOWN = '';
+ public const CHIMPLE_STATUS_NEW = 'NEW';
+ public const CHIMPLE_STATUS_PROCESSING = 'PROCESSING';
+ public const CHIMPLE_STATUS_BATCHED = 'BATCHED';
+ public const CHIMPLE_STATUS_SUCCESS = 'SUCCESS';
+ public const CHIMPLE_STATUS_FAIL = 'FAIL';
- const MAILCHIMP_SUBSCRIBER_PENDING = 'pending';
- const MAILCHIMP_SUBSCRIBER_SUBSCRIBED = 'subscribed';
- const MAILCHIMP_SUBSCRIBER_UNSUBSCRIBED = 'unsubscribed';
- const MAILCHIMP_SUBSCRIBER_CLEANED = 'cleaned';
+ public const MAILCHIMP_SUBSCRIBER_PENDING = 'pending';
+ public const MAILCHIMP_SUBSCRIBER_SUBSCRIBED = 'subscribed';
+ public const MAILCHIMP_SUBSCRIBER_UNSUBSCRIBED = 'unsubscribed';
+ public const MAILCHIMP_SUBSCRIBER_CLEANED = 'cleaned';
- const MAILCHIMP_TAG_INACTIVE = 'inactive';
- const MAILCHIMP_TAG_ACTIVE = 'active';
+ public const MAILCHIMP_TAG_INACTIVE = 'inactive';
+ public const MAILCHIMP_TAG_ACTIVE = 'active';
- const MAILCHIMP_EMAIL_TYPE_HTML = 'html';
- const MAILCHIMP_EMAIL_TYPE_TEXT = 'text';
+ public const MAILCHIMP_EMAIL_TYPE_HTML = 'html';
+ public const MAILCHIMP_EMAIL_TYPE_TEXT = 'text';
/**
* @var string
@@ -230,7 +230,7 @@ public function getCMSFields()
&& !empty($this->Status)) {
// these status are readonly in CMS fields
$status_field = $status_field->performReadonlyTransformation();
- } else if($this->Status == self::CHIMPLE_STATUS_PROCESSING) {
+ } elseif($this->Status == self::CHIMPLE_STATUS_PROCESSING) {
// stuck processing - can reset to new
$status_field->setDescription(
_t(
@@ -243,7 +243,7 @@ public function getCMSFields()
self::CHIMPLE_STATUS_NEW => _t(__CLASS__ . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
self::CHIMPLE_STATUS_PROCESSING => _t(__CLASS__ . '.STATUS_PROCESSING', 'PROCESSING (the subscriber is in the process of being subscribed)'),
]);
- } else if($this->Status == self::CHIMPLE_STATUS_FAIL) {
+ } elseif($this->Status == self::CHIMPLE_STATUS_FAIL) {
// handling when failed
$status_field->setDescription(
_t(
@@ -379,7 +379,8 @@ public function onBeforeWrite()
* By default MergeFields doesn't allow HTML tags as keys or as values
* @param array $meta
*/
- public function updateMergeFields(array $meta) {
+ public function updateMergeFields(array $meta)
+ {
if(empty($meta)) {
return;
}
@@ -390,8 +391,8 @@ public function updateMergeFields(array $meta) {
// ignore values that cannot be saved
continue;
}
- $key = strtoupper( trim( strip_tags($k) ) );
- $value = trim( strip_tags($v) );
+ $key = strtoupper(trim(strip_tags($k)));
+ $value = trim(strip_tags($v));
$data[ $key ] = $value;
}
$this->MergeFields = $data;
@@ -417,7 +418,8 @@ public function getSurnameFromName()
/**
* Get the API client
*/
- public static function api() : MailchimpApiClient {
+ public static function api(): MailchimpApiClient
+ {
// already set up..
if(self::$mailchimp instanceof MailchimpApiClient) {
return self::$mailchimp;
@@ -433,7 +435,8 @@ public static function api() : MailchimpApiClient {
/**
* @deprecated use self::api() instead
*/
- public function getMailchimp() {
+ public function getMailchimp()
+ {
return self::api();
}
@@ -452,7 +455,8 @@ public function getMailchimpListId()
/**
* Applies merge fields prior to subscription attempt
*/
- protected function applyMergeFields(): array {
+ protected function applyMergeFields(): array
+ {
$merge_fields = [];
// get subscriber meta data
@@ -497,7 +501,8 @@ protected function applyMergeFields(): array {
/**
* Get the default subscription record data for adding/updating member in list
*/
- public function getSubscribeRecord() : array {
+ public function getSubscribeRecord(): array
+ {
// merge fields to send
$merge_fields = $this->applyMergeFields();
// ensure sane email type either html or text, default html if invalid
@@ -516,7 +521,8 @@ public function getSubscribeRecord() : array {
/**
* Return tags for this subscriber
*/
- public function getSubscriberTags() {
+ public function getSubscriberTags()
+ {
$tags = $this->Tags->getValue();
if(!is_array($tags)) {
return [];
@@ -528,8 +534,9 @@ public function getSubscriberTags() {
/**
* Called after a successful subscription, obfuscates email, name and surname
*/
- private function obfuscate() {
- $obfuscate = function(string $in) : string {
+ private function obfuscate()
+ {
+ $obfuscate = function (string $in): string {
$length = strlen($in);
if($length == 0) {
return "";
@@ -554,7 +561,8 @@ private function obfuscate() {
/**
* Get the hash that is used as the MC subscribed Id value
*/
- public static function getMailchimpSubscribedId($email): string {
+ public static function getMailchimpSubscribedId($email): string
+ {
if(!is_string($email) || !$email) {
return '';
} else {
@@ -568,7 +576,8 @@ public static function getMailchimpSubscribedId($email): string {
* @param string $email an email address, this is hashed using the MC hashing strategy
* @param string $api_key @deprecated
*/
- public static function checkExistsInList(string $list_id, string $email, string $api_key = '') : array|false {
+ public static function checkExistsInList(string $list_id, string $email, string $api_key = ''): array|false
+ {
// sanity check on input
if(!$email) {
@@ -590,7 +599,7 @@ public static function checkExistsInList(string $list_id, string $email, string
}
// attempt to get the subscriber
- if( $hash = self::getMailchimpSubscribedId($email) ) {
+ if($hash = self::getMailchimpSubscribedId($email)) {
$result = self::api()->get(
"lists/{$list_id}/members/{$hash}"
);
@@ -607,7 +616,7 @@ public static function checkExistsInList(string $list_id, string $email, string
/**
* Subscribe *this* particular record
*/
- public function subscribe() : bool
+ public function subscribe(): bool
{
try {
@@ -694,7 +703,8 @@ public function subscribe() : bool
* @param bool $force whether to get the tags from the remote or use previously retrieved tags
* @param int $count the number of records to return per request
*/
- private function getCurrentSubscriberTags(bool $force = false, int $count = 10) : array {
+ private function getCurrentSubscriberTags(bool $force = false, int $count = 10): array
+ {
// if already retrieved,
if(is_array($this->_cache_tags) && !$force) {
@@ -719,7 +729,7 @@ private function getCurrentSubscriberTags(bool $force = false, int $count = 10)
$tags = isset($result['tags']) && is_array($result['tags']) ? $result['tags'] : [];
// populate the list of tags
- $walker = function($value, $key) use (&$list) {
+ $walker = function ($value, $key) use (&$list) {
$list[] = $value['name'];
};
array_walk($tags, $walker);
@@ -746,7 +756,8 @@ private function getCurrentSubscriberTags(bool $force = false, int $count = 10)
/**
* Modify this subscriber's tags based on their current tags
*/
- protected function modifySubscriberTags() : bool {
+ protected function modifySubscriberTags(): bool
+ {
$current = $this->getCurrentSubscriberTags();
$tags_for_update = $this->getSubscriberTags();
@@ -756,7 +767,7 @@ protected function modifySubscriberTags() : bool {
// if enabled: remove tags that do not exist in the modification list
if($this->config()->get('remove_subscriber_tags')) {
- $inactive = array_diff($current,$tags_for_update);
+ $inactive = array_diff($current, $tags_for_update);
// Mark removed tags as inactive
foreach($inactive as $tag) {
$params['tags'][] = [
@@ -767,7 +778,7 @@ protected function modifySubscriberTags() : bool {
}
// Retain active tags that are in both lists
- $retained = array_intersect($current,$tags_for_update);
+ $retained = array_intersect($current, $tags_for_update);
foreach($retained as $tag) {
$params['tags'][] = [
'name' => $tag,
@@ -808,7 +819,7 @@ protected function modifySubscriberTags() : bool {
* Batch subscribe via API - hit from MailchimpSubscribeJob
* Retrieve all subscribers marked new and attempt to subscribe them
*/
- public static function batch_subscribe($limit = 100, $report_only = false) : array
+ public static function batch_subscribe($limit = 100, $report_only = false): array
{
$results = [];
try {
diff --git a/src/Traits/SubscriptionForm.php b/src/Traits/SubscriptionForm.php
index 99aa0cd..91f5fcc 100644
--- a/src/Traits/SubscriptionForm.php
+++ b/src/Traits/SubscriptionForm.php
@@ -7,12 +7,13 @@
/**
* Trait for use by subscription forms
*/
-trait SubscriptionForm {
-
+trait SubscriptionForm
+{
/**
* This method can be used to check the cache-able status of the form
*/
- public function checkCanBeCached() : bool {
+ public function checkCanBeCached(): bool
+ {
return $this->canBeCached();
}
diff --git a/tests/ChimpleConfigTest.php b/tests/ChimpleConfigTest.php
index e279202..e3b37b4 100644
--- a/tests/ChimpleConfigTest.php
+++ b/tests/ChimpleConfigTest.php
@@ -22,7 +22,6 @@
*/
class ChimpleConfigTest extends SapphireTest
{
-
/**
* @inheritdoc
*/
@@ -46,7 +45,8 @@ class ChimpleConfigTest extends SapphireTest
/**
* @inheritdoc
*/
- public function setUp() : void {
+ public function setUp(): void
+ {
parent::setUp();
// Create default configuration
@@ -71,7 +71,8 @@ public function setUp() : void {
$config->write();
}
- protected function getMailchimpConfig() {
+ protected function getMailchimpConfig()
+ {
// get config for the test list
$config = MailchimpConfig::get()->filter(['MailchimpListId' => $this->test_list_id])->first();
@@ -84,10 +85,10 @@ protected function getMailchimpConfig() {
// list check
$list_id = $config->getMailchimpListId();
$this->assertNotEquals($list_id, $this->default_list_id, "List Id should not be the same as default list id");
- $this->assertTrue( $config->HasMailchimpListId(), "Config should have a list id");
+ $this->assertTrue($config->HasMailchimpListId(), "Config should have a list id");
// test config retrieval via Code
- $retrieved_config = MailchimpConfig::getConfig('','', $config->Code);
+ $retrieved_config = MailchimpConfig::getConfig('', '', $config->Code);
$this->assertEquals($retrieved_config->ID, $config->ID, "Configs should be the same");
return $retrieved_config;
@@ -105,40 +106,41 @@ public function testConfiguration()
// test configuration form retrieval
$form = $config->SubscribeForm($forceXhr);
- $this->assertTrue( $form instanceof Form, "SubscribeForm is not an instance of Form");
+ $this->assertTrue($form instanceof Form, "SubscribeForm is not an instance of Form");
- $this->assertEquals( 1, $form->getAttribute('data-xhr'), "Form should have XHR attribute enabled" );
+ $this->assertEquals(1, $form->getAttribute('data-xhr'), "Form should have XHR attribute enabled");
$fields = $form->Fields();
$email = $fields->dataFieldByName('Email');
- $this->assertTrue( $email instanceof EmailField, "Email field is not an email field");
+ $this->assertTrue($email instanceof EmailField, "Email field is not an email field");
$name = $fields->dataFieldByName('Name');
- $this->assertTrue( $email instanceof TextField, "Name field is not an text field");
+ $this->assertTrue($email instanceof TextField, "Name field is not an text field");
$token_name = SecurityToken::get_default_name();
$token = $fields->dataFieldByName($token_name);
- $this->assertTrue( $token instanceof HiddenField, "{$token_name} field is not present");
+ $this->assertTrue($token instanceof HiddenField, "{$token_name} field is not present");
$code_field = $fields->dataFieldByName('code');
- $this->assertTrue( $code_field instanceof HiddenField, "'code' field is not present");
+ $this->assertTrue($code_field instanceof HiddenField, "'code' field is not present");
$code_value = $code_field->dataValue();
$this->assertEquals($code_value, $config->Code, "Code value in form is not the same as config value");
$static_form = MailchimpConfig::get_chimple_subscribe_form($code_value);
- $this->assertTrue( $static_form instanceof DBHTMLText, "Static form for code {$code_value} was not returned");
+ $this->assertTrue($static_form instanceof DBHTMLText, "Static form for code {$code_value} was not returned");
$needle = " value=\"{$code_value}\" ";
- $this->assertTrue( str_contains($static_form->forTemplate(), $needle), "Missing {$code_value} input from form HTML");
+ $this->assertTrue(str_contains($static_form->forTemplate(), $needle), "Missing {$code_value} input from form HTML");
}
- public function testCanBeCached() {
+ public function testCanBeCached()
+ {
Config::modify()->set(XhrSubscribeForm::class, 'disable_security_token', true);
@@ -147,59 +149,61 @@ public function testCanBeCached() {
// test forcing XHR
$forceXhr = true;
$form = $config->SubscribeForm($forceXhr);
- $this->assertTrue( $form->checkCanBeCached() );
+ $this->assertTrue($form->checkCanBeCached());
// test not forcing XHR
$forceXhr = false;
$form = $config->SubscribeForm($forceXhr);
- $this->assertFalse( $form->checkCanBeCached() );
+ $this->assertFalse($form->checkCanBeCached());
// test using config value
// config is turned off
$config->UseXHR = 0;
$form = $config->SubscribeForm();// default null value
- $this->assertFalse( $form->checkCanBeCached() );
+ $this->assertFalse($form->checkCanBeCached());
// config turned on
$config->UseXHR = 1;
$form = $config->SubscribeForm();// default null value
- $this->assertTrue( $form->checkCanBeCached() );
+ $this->assertTrue($form->checkCanBeCached());
}
- public function testSubscribeFormTemplateVariable() {
+ public function testSubscribeFormTemplateVariable()
+ {
$config = $this->getMailchimpConfig();
$config->UseXHR = 0;
$config->write();
// Use config value
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
// template override
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '1');
- $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '0');
- $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
}
- public function testGlobalSubscribeFormTemplateVariable() {
+ public function testGlobalSubscribeFormTemplateVariable()
+ {
$config = $this->getMailchimpConfig();
$config->UseXHR = 0;
$config->write();
// Use config value
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue( !str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue( str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
}
}
diff --git a/tests/ChimpleFunctionalTest.php b/tests/ChimpleFunctionalTest.php
index 11a95ad..4792d85 100644
--- a/tests/ChimpleFunctionalTest.php
+++ b/tests/ChimpleFunctionalTest.php
@@ -24,7 +24,6 @@
*/
class ChimpleFunctionalTest extends FunctionalTest
{
-
/**
* @inheritdoc
*/
@@ -51,19 +50,21 @@ class ChimpleFunctionalTest extends FunctionalTest
protected $test_form_code = 'functionalformcode';
- public function setUp() : void {
+ public function setUp(): void
+ {
parent::setUp();
// Inject test form
Injector::inst()->registerService(
- new TestSubscribeForm(), SubscribeForm::class
+ new TestSubscribeForm(),
+ SubscribeForm::class
);
// Suppress themes
SSViewer::set_themes(
[
- SSViewer::DEFAULT_THEME
+ SSViewer::DEFAULT_THEME
]
);
@@ -115,7 +116,7 @@ public function testFormSubmission()
'Status' => MailchimpSubscriber::CHIMPLE_STATUS_NEW
])->first();
- $this->assertTrue( $subscriber && $subscriber->exists() );
+ $this->assertTrue($subscriber && $subscriber->exists());
});
diff --git a/tests/ChimpleSubscriberTest.php b/tests/ChimpleSubscriberTest.php
index 84dee4c..9d8493a 100644
--- a/tests/ChimpleSubscriberTest.php
+++ b/tests/ChimpleSubscriberTest.php
@@ -16,7 +16,6 @@
*/
class ChimpleSubscriberTest extends SapphireTest
{
-
use Configurable;
protected $usesDatabase = true;
@@ -98,21 +97,21 @@ public function testSubscriber()
$subscribe_record = $subscriber->getSubscribeRecord();
- $this->assertTrue( is_array($subscribe_record), "Record is not an array of values");
+ $this->assertTrue(is_array($subscribe_record), "Record is not an array of values");
- $this->assertTrue( !empty($subscribe_record), "Record is empty");
+ $this->assertTrue(!empty($subscribe_record), "Record is empty");
- $this->assertTrue( isset($subscribe_record['merge_fields']), "Record merge_fields is not set");
+ $this->assertTrue(isset($subscribe_record['merge_fields']), "Record merge_fields is not set");
- $this->assertTrue( !empty($subscribe_record['email_type']), "Record email_type is empty");
+ $this->assertTrue(!empty($subscribe_record['email_type']), "Record email_type is empty");
- $this->assertEquals( $subscriber->Email, $subscribe_record['email_address'], "Subscribed email_address value is not the same as subsciber record Email field value");
+ $this->assertEquals($subscriber->Email, $subscribe_record['email_address'], "Subscribed email_address value is not the same as subsciber record Email field value");
// check merge fields
$sync_fields = $subscriber->config()->get('sync_fields');
$merge_fields = $subscribe_record['merge_fields'];
- foreach($sync_fields as $field => $tag ) {
- $this->assertTrue( isset($merge_fields[ $tag ]) && $merge_fields[ $tag ] = $subscriber->getField($field), "Merge field tag {$tag} value does not match subscriber {$field} value");
+ foreach($sync_fields as $field => $tag) {
+ $this->assertTrue(isset($merge_fields[ $tag ]) && $merge_fields[ $tag ] = $subscriber->getField($field), "Merge field tag {$tag} value does not match subscriber {$field} value");
}
$email = $subscriber->Email;
@@ -142,7 +141,7 @@ public function testSubscriber()
$this->assertEquals(count($tags), count($mc_record['tags']), "Tag count mismatch");
$mc_tags_list = [];
- array_walk($mc_record['tags'], function($value, $key) use (&$mc_tags_list) {
+ array_walk($mc_record['tags'], function ($value, $key) use (&$mc_tags_list) {
$mc_tags_list[] = $value['name'];
});
diff --git a/tests/TestSubscribeForm.php b/tests/TestSubscribeForm.php
index 76edd78..b6b43d2 100644
--- a/tests/TestSubscribeForm.php
+++ b/tests/TestSubscribeForm.php
@@ -8,12 +8,13 @@
/**
* Test subscribe form handling
*/
-class TestSubscribeForm extends SubscribeForm implements TestOnly {
-
+class TestSubscribeForm extends SubscribeForm implements TestOnly
+{
/**
* No need to spam protection on tests
*/
- public function enableSpamProtection() {
+ public function enableSpamProtection()
+ {
return null;
}
}
From f1b0099132a6a646f85e55f09c5c78fca0ade3b5 Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Thu, 8 Aug 2024 02:27:41 +0000
Subject: [PATCH 26/41] [rector] Automated updates generated by rector
configuration
---
src/Controllers/ChimpleController.php | 118 +++++-----
src/Controllers/MailchimpAdmin.php | 6 +-
.../DisableSecurityTokenExtension.php | 2 +-
src/Extensions/PageExtension.php | 4 +-
src/Extensions/SiteConfigExtension.php | 18 +-
src/Forms/XhrSubscribeForm.php | 5 +-
src/Jobs/MailchimpCleanupJob.php | 28 ++-
src/Jobs/MailchimpSubscribeJob.php | 31 ++-
.../Elements/ElementChimpleSubscribe.php | 50 +++--
src/Models/MailchimpConfig.php | 110 ++++++----
src/Models/MailchimpSubscriber.php | 201 ++++++++++--------
tests/ChimpleConfigTest.php | 25 +--
tests/ChimpleFunctionalTest.php | 7 +-
tests/ChimpleSubscriberTest.php | 22 +-
tests/TestSubscribeForm.php | 2 +-
15 files changed, 333 insertions(+), 296 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index caa94c6..0a15284 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -31,20 +31,11 @@
*/
class ChimpleController extends PageController
{
- /**
- * @var string
- */
- private static $url_segment = 'mc-subscribe/v1';
+ private static string $url_segment = 'mc-subscribe/v1';
- /**
- * @var bool
- */
- private static $hide_generic_form = true;
+ private static bool $hide_generic_form = true;
- /**
- * @var array
- */
- private static $allowed_actions = [
+ private static array $allowed_actions = [
'SubscribeForm',
'XhrSubscribeForm'
];
@@ -66,14 +57,11 @@ public function index()
public function pageTitle($complete = null)
{
- switch($complete) {
- case 'y':
- return _t(__CLASS__. '.DEFAULT_TITLE_SUCCESSFUL', 'Thanks for subscribing');
- case 'n':
- return _t(__CLASS__. '.DEFAULT_TITLE_NOT_SUCCESSFUL', 'Sorry, there was an error');
- default:
- return _t(__CLASS__. '.DEFAULT_TITLE', 'Subscribe');
- }
+ return match ($complete) {
+ 'y' => _t(self::class. '.DEFAULT_TITLE_SUCCESSFUL', 'Thanks for subscribing'),
+ 'n' => _t(self::class. '.DEFAULT_TITLE_NOT_SUCCESSFUL', 'Sorry, there was an error'),
+ default => _t(self::class. '.DEFAULT_TITLE', 'Subscribe'),
+ };
}
public function Link($action = null)
@@ -120,11 +108,8 @@ public function setFormNameSuffix(string $suffix = ''): self
*/
public function getFormNameSuffix(): string
{
- if($this->formNameSuffix) {
- $suffix = "_{$this->formNameSuffix}";
- } else {
- $suffix = "";
- }
+ $suffix = $this->formNameSuffix ? "_{$this->formNameSuffix}" : "";
+
return $suffix;
}
@@ -133,11 +118,8 @@ public function getFormNameSuffix(): string
*/
public function getSubscriptionForm($useXhr = false): SubscribeForm|XhrSubscribeForm|null
{
- if($useXhr) {
- $form = $this->XhrSubscribeForm();
- } else {
- $form = $this->SubscribeForm();
- }
+ $form = $useXhr ? $this->XhrSubscribeForm() : $this->SubscribeForm();
+
return $form;
}
@@ -229,17 +211,16 @@ protected function configureForm(SubscribeForm $form): SubscribeForm
*/
protected function getFields(): FieldList
{
- $fields = FieldList::create(
- $name = TextField::create('Name', _t(__CLASS__. '.NAME', 'Name'))
- ->setAttribute('placeholder', _t(__CLASS__. '.YOUR_NAME', 'Your name'))
- ->setAttribute('title', _t(__CLASS__. '.NAME', 'Name'))
+ return FieldList::create(
+ $name = TextField::create('Name', _t(self::class. '.NAME', 'Name'))
+ ->setAttribute('placeholder', _t(self::class. '.YOUR_NAME', 'Your name'))
+ ->setAttribute('title', _t(self::class. '.NAME', 'Name'))
->setAttribute('required', 'required'),
- $email = EmailField::create('Email', _t(__CLASS__. '.EMAIL', 'Email'))
- ->setAttribute('placeholder', _t(__CLASS__. '.EMAIL_ADDRESS', 'Email address'))
- ->setAttribute('title', _t(__CLASS__. '.EMAIL', 'Email'))
+ $email = EmailField::create('Email', _t(self::class. '.EMAIL', 'Email'))
+ ->setAttribute('placeholder', _t(self::class. '.EMAIL_ADDRESS', 'Email address'))
+ ->setAttribute('title', _t(self::class. '.EMAIL', 'Email'))
->setAttribute('required', 'required')
);
- return $fields;
}
/**
@@ -247,14 +228,13 @@ protected function getFields(): FieldList
*/
protected function getActions(): FieldList
{
- $actions = FieldList::create(
+ return FieldList::create(
FormAction::create(
'subscribe',
- _t(__CLASS__ . '.SUBSCRIBE', 'Subscribe')
+ _t(self::class . '.SUBSCRIBE', 'Subscribe')
)->setUseButtonTag(true)
->addExtraClass('signup')
);
- return $actions;
}
/**
@@ -272,10 +252,10 @@ protected function getValidator(): ?Validator
*/
protected function getCallbackForXhrValidation(): callable
{
- return function (ValidationResult $result) {
+ return function (ValidationResult $result): \SilverStripe\Control\HTTPResponse {
// Fail, using the first message returned from the validation result
$messages = $result->getMessages();
- $message = (!empty($messages[0]['message']) ? $messages[0]['message'] : '');
+ $message = (empty($messages[0]['message']) ? '' : $messages[0]['message']);
return $this->xhrError(400, $message);
};
}
@@ -301,30 +281,30 @@ protected function getCallbackForValidation(SubscribeForm $form): callable
/**
* Handle errors, based on the request type
*/
- private function handleError($code, $error_message, Form $form = null)
+ private function handleError($code, $error_message, Form $form = null): ?\SilverStripe\Control\HTTPResponse
{
if($this->request->isAjax()) {
return $this->xhrError($code, $error_message);
- } elseif($form) {
+ } elseif($form instanceof \SilverStripe\Forms\Form) {
// set session error on the form
$form->sessionError($error_message, ValidationResult::TYPE_ERROR);
}
- return;
+ return null;
}
/**
* Handle successful submissions, based on the request type
*/
- private function handleSuccess($code, $message, Form $form = null)
+ private function handleSuccess(int $code, Form $form = null): ?\SilverStripe\Control\HTTPResponse
{
$success_message = Config::inst()->get(MailchimpConfig::class, 'success_message');
if($this->request->isAjax()) {
- return $this->xhrSuccess($code, $message, $success_message);
- } elseif($form) {
+ return $this->xhrSuccess($code, $success_message);
+ } elseif($form instanceof \SilverStripe\Forms\Form) {
// set session message on the form
$form->sessionMessage($success_message, ValidationResult::TYPE_GOOD);
}
- return;
+ return null;
}
/**
@@ -342,14 +322,14 @@ public function subscribe($data = [], Form $form = null)
$error_message = "";
$email = $data['Email'] ?? '';
- if(!$form) {
+ if(!$form instanceof \SilverStripe\Forms\Form) {
throw new RequestException("Forbidden", 403);
}
if($code === "") {
// fail with error
$error_message = _t(
- __CLASS__ . '.NO_CODE',
+ self::class . '.NO_CODE',
"No code was provided"
);
$error_code = 400;// default to invalid data
@@ -361,7 +341,7 @@ public function subscribe($data = [], Form $form = null)
$enabled = MailchimpConfig::isEnabled();
if(!$enabled) {
$error_message = _t(
- __CLASS__ . '.SUBSCRIPTIONS_NOT_AVAILABLE',
+ self::class . '.SUBSCRIPTIONS_NOT_AVAILABLE',
"Subscriptions are not available at the moment"
);
}
@@ -371,15 +351,15 @@ public function subscribe($data = [], Form $form = null)
if ($email === '') {
// fail with error
$error_message = _t(
- __CLASS__ . '.NO_EMAIL_ADDRESS',
+ self::class . '.NO_EMAIL_ADDRESS',
"No e-mail address was provided"
);
} elseif (!Email::is_valid_address($email)) {
$error_message = _t(
- __CLASS__ . '.INVALID_EMAIL_ADDRESS',
+ self::class . '.INVALID_EMAIL_ADDRESS',
"Please provide a valid e-mail address, '{email}' is not valid",
[
- 'email' => htmlspecialchars($data['Email'])
+ 'email' => htmlspecialchars((string) $data['Email'])
]
);
}
@@ -387,27 +367,27 @@ public function subscribe($data = [], Form $form = null)
if (!$error_message) {
// check code provided
- if (!$code) {
+ if ($code === '' || $code === '0') {
$error_message = _t(
- __CLASS__ . ".GENERIC_ERROR_1",
+ self::class . ".GENERIC_ERROR_1",
"Sorry, the sign-up could not be completed"
);
} else {
$mc_config = MailchimpConfig::getConfig('', '', $code);
- if ($mc_config) {
+ if ($mc_config instanceof \NSWDPC\Chimple\Models\MailchimpConfig) {
$list_id = $mc_config->getMailchimpListId();
} else {
$error_message = _t(
- __CLASS__ . ".GENERIC_ERROR_2",
+ self::class . ".GENERIC_ERROR_2",
"Sorry, the sign-up could not be completed"
);
}
}
}
- if (!$list_id) {
+ if ($list_id === null || $list_id === '' || $list_id === '0') {
$error_message = _t(
- __CLASS__ . ".GENERIC_ERROR_3",
+ self::class . ".GENERIC_ERROR_3",
"Sorry, the sign-up could not be completed"
);
}
@@ -436,7 +416,7 @@ public function subscribe($data = [], Form $form = null)
$sub->Email = $email;
$sub->MailchimpListId = $list_id;//list they are subscribing to
$sub->Status = MailchimpSubscriber::CHIMPLE_STATUS_NEW;
- $sub->Tags = $mc_config ? $mc_config->Tags : null;
+ $sub->Tags = $mc_config instanceof \NSWDPC\Chimple\Models\MailchimpConfig ? $mc_config->Tags : null;
$sub_id = $sub->write();
if (!$sub_id) {
throw new RequestException("Bad Gateway", 502);
@@ -450,7 +430,7 @@ public function subscribe($data = [], Form $form = null)
}
// handle a successful subscription
- $response = $this->handleSuccess(200, "OK", $form);
+ $response = $this->handleSuccess(200, $form);
if($response && ($response instanceof HTTPResponse)) {
// handle responses for e.g XHR
return $response;
@@ -466,7 +446,7 @@ public function subscribe($data = [], Form $form = null)
} catch (RequestException $e) {
$error_message = $e->getMessage();
$error_code = $e->getCode();
- } catch (\Exception $e) {
+ } catch (\Exception) {
// general exceptin
$error_message = Config::inst()->get(MailchimpConfig::class, 'error_message');
$error_code = 500;
@@ -491,9 +471,9 @@ public function subscribe($data = [], Form $form = null)
/**
* Return error response for XHR
*/
- private function xhrError($code = 500, $message = "", $description = ""): HTTPResponse
+ private function xhrError($code = 500, $message = ""): HTTPResponse
{
- $response = new HTTPResponse();
+ $response = \SilverStripe\Control\HTTPResponse::create();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
$response->addHeader('X-Submission-OK', '0');
@@ -504,9 +484,9 @@ private function xhrError($code = 500, $message = "", $description = ""): HTTPRe
/**
* Return success response for XHR
*/
- private function xhrSuccess($code = 200, $message = "", $description = ""): HTTPResponse
+ private function xhrSuccess(int $code = 200, $description = ""): HTTPResponse
{
- $response = new HTTPResponse();
+ $response = \SilverStripe\Control\HTTPResponse::create();
$response->setStatusCode($code);
$response->addHeader('Content-Type', 'application/json');
$response->addHeader('X-Submission-OK', '1');
diff --git a/src/Controllers/MailchimpAdmin.php b/src/Controllers/MailchimpAdmin.php
index 8d40dc6..3f65815 100644
--- a/src/Controllers/MailchimpAdmin.php
+++ b/src/Controllers/MailchimpAdmin.php
@@ -13,12 +13,12 @@
*/
class MailchimpAdmin extends ModelAdmin
{
- private static $managed_models = [
+ private static array $managed_models = [
MailchimpSubscriber::class,
MailchimpConfig::class
];
- private static $menu_title = 'Mailchimp';
+ private static string $menu_title = 'Mailchimp';
- private static $url_segment = 'mailchimp';
+ private static string $url_segment = 'mailchimp';
}
diff --git a/src/Extensions/DisableSecurityTokenExtension.php b/src/Extensions/DisableSecurityTokenExtension.php
index 2321f1b..eb4bc68 100644
--- a/src/Extensions/DisableSecurityTokenExtension.php
+++ b/src/Extensions/DisableSecurityTokenExtension.php
@@ -14,6 +14,6 @@ class DisableSecurityTokenExtension extends Extension
{
public function updateChimpleSubscribeForm()
{
- $this->owner->disableSecurityToken();
+ $this->getOwner()->disableSecurityToken();
}
}
diff --git a/src/Extensions/PageExtension.php b/src/Extensions/PageExtension.php
index 0384509..2d83c05 100644
--- a/src/Extensions/PageExtension.php
+++ b/src/Extensions/PageExtension.php
@@ -20,6 +20,7 @@ public function ChimpleGlobalSubscribeForm(): ?SubscribeForm
if ($config) {
return $config->SubscribeForm();
}
+
return null;
}
@@ -30,9 +31,10 @@ public function ChimpleGlobalSubscribeForm(): ?SubscribeForm
public function ChimpleSubscribeForm(string $config_code): ?SubscribeForm
{
$config = MailchimpConfig::getConfig('', '', $config_code);
- if($config) {
+ if($config instanceof \NSWDPC\Chimple\Models\MailchimpConfig) {
return $config->SubscribeForm();
}
+
return null;
}
}
diff --git a/src/Extensions/SiteConfigExtension.php b/src/Extensions/SiteConfigExtension.php
index d014b12..64b9d3b 100644
--- a/src/Extensions/SiteConfigExtension.php
+++ b/src/Extensions/SiteConfigExtension.php
@@ -11,14 +11,15 @@
class SiteConfigExtension extends DataExtension
{
- private static $db = [
+ private static array $db = [
'MailchimpEnabled' => 'Boolean'
];
- private static $has_one = [
+ private static array $has_one = [
'MailchimpConfig' => MailchimpConfig::class // global element for configuration
];
+ #[\Override]
public function updateCmsFields(FieldList $fields)
{
$fields->addFieldsToTab(
@@ -26,25 +27,24 @@ public function updateCmsFields(FieldList $fields)
[
CheckboxField::create(
'MailchimpEnabled',
- _t(__CLASS__. '.MAILCHIMP_ENABLED', 'Mailchimp subscriptions enabled')
+ _t(self::class. '.MAILCHIMP_ENABLED', 'Mailchimp subscriptions enabled')
),
DropdownField::create(
'MailchimpConfigID',
- _t(__CLASS__. '.DEFAULT_MAILCHIMP_CONFIG', 'Default Mailchimp configuration'),
+ _t(self::class. '.DEFAULT_MAILCHIMP_CONFIG', 'Default Mailchimp configuration'),
MailchimpConfig::get()->map('ID', 'TitleCode')
)->setEmptyString('')
]
);
}
+ #[\Override]
public function onAfterWrite()
{
parent::onAfterWrite();
- if($this->owner->MailchimpConfigID) {
- if($config = MailchimpConfig::get()->byId($this->owner->MailchimpConfigID)) {
- $config->IsGlobal = 1;
- $config->write();
- }
+ if ($this->getOwner()->MailchimpConfigID && ($config = MailchimpConfig::get()->byId($this->getOwner()->MailchimpConfigID))) {
+ $config->IsGlobal = 1;
+ $config->write();
}
}
diff --git a/src/Forms/XhrSubscribeForm.php b/src/Forms/XhrSubscribeForm.php
index d0a718c..aabfdbe 100644
--- a/src/Forms/XhrSubscribeForm.php
+++ b/src/Forms/XhrSubscribeForm.php
@@ -17,9 +17,8 @@ class XhrSubscribeForm extends SubscribeForm
{
/**
* Set to true if forms of this class will appear on a publicly cacheable page
- * @var bool
*/
- private static $disable_security_token = false;
+ private static bool $disable_security_token = false;
public function __construct(
RequestHandler $controller = null,
@@ -37,6 +36,7 @@ public function __construct(
/**
* @inheritdoc
*/
+ #[\Override]
protected function canBeCached()
{
$token = $this->getSecurityToken();
@@ -51,6 +51,7 @@ protected function canBeCached()
* @inheritdoc
* Add attributes
*/
+ #[\Override]
protected function getDefaultAttributes(): array
{
$attributes = parent::getDefaultAttributes();
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 61f79ea..ffa38b0 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -19,7 +19,7 @@ class MailchimpCleanupJob extends AbstractQueuedJob implements QueuedJob
{
use Configurable;
- private static $run_in_minutes = 30;
+ private static int $run_in_minutes = 30;
public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
{
@@ -28,11 +28,12 @@ public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
$this->limit = $limit;
}
+ #[\Override]
public function getTitle()
{
return sprintf(
_t(
- __CLASS__ . '.TITLE',
+ self::class . '.TITLE',
"Mailchimp cleanup job - minutes=%s limit=%s report_only=%s"
),
$this->minutes_ago,
@@ -41,24 +42,26 @@ public function getTitle()
);
}
+ #[\Override]
public function getJobType()
{
return QueuedJob::QUEUED;
}
+ #[\Override]
public function setup()
{
$this->totalSteps = 1;
}
+ #[\Override]
public function process()
{
$this->processSubscriptions();
$this->isComplete = true;
- return;
}
- private function processSubscriptions()
+ private function processSubscriptions(): bool
{
$prune_datetime = new DateTime();
$minutes = $this->minutes_ago;
@@ -87,15 +90,16 @@ private function processSubscriptions()
$subscriber->delete();
$success_deletes++;
}
+
$this->addMessage("Deleted {$success_deletes} subscribers with status " . MailchimpSubscriber::CHIMPLE_STATUS_SUCCESS);
}
-
-
- $this->currentStep = $this->totalSteps = $success_deletes;
+ $this->currentStep = $success_deletes;
+ $this->totalSteps = $success_deletes;
// remove stale failed subscriptions older than 7 days
$fail_datetime = new DateTime();
$fail_datetime->modify('-7 days');
+
$failed = MailchimpSubscriber::get()->filter([
'Status' => MailchimpSubscriber::CHIMPLE_STATUS_FAIL,
'Created:LessThan' => $fail_datetime->format('Y-m-d H:i:s')
@@ -109,11 +113,11 @@ private function processSubscriptions()
$failed_subscriber->delete();
$failed_deletes++;
}
+
$this->addMessage("Deleted {$failed_deletes} subscribers with status " . MailchimpSubscriber::CHIMPLE_STATUS_FAIL);
}
-
-
- $this->currentStep = $this->totalSteps = ($success_deletes + $failed_deletes);
+ $this->currentStep = $success_deletes + $failed_deletes;
+ $this->totalSteps = $success_deletes + $failed_deletes;
return true;
}
@@ -121,16 +125,18 @@ private function processSubscriptions()
/**
* Get next configured run time
*/
- private function getNextRunMinutes()
+ private function getNextRunMinutes(): int
{
$minutes = (int)$this->config()->get('run_in_minutes');
if ($minutes <= 2) {
// min every 2 minutes
$minutes = 2;
}
+
return $minutes;
}
+ #[\Override]
public function afterComplete()
{
$run_datetime = new DateTime();
diff --git a/src/Jobs/MailchimpSubscribeJob.php b/src/Jobs/MailchimpSubscribeJob.php
index 5c2a6a7..ca9c0b7 100644
--- a/src/Jobs/MailchimpSubscribeJob.php
+++ b/src/Jobs/MailchimpSubscribeJob.php
@@ -14,8 +14,9 @@ class MailchimpSubscribeJob extends AbstractQueuedJob implements QueuedJob
{
use Configurable;
- private static $run_in_seconds = 60;
- private static $default_limit = 100;
+ private static int $run_in_seconds = 60;
+
+ private static int $default_limit = 100;
public function __construct($limit = 100, $report_only = 0)
{
@@ -23,37 +24,40 @@ public function __construct($limit = 100, $report_only = 0)
$this->limit = (int)$limit;
}
+ #[\Override]
public function getTitle()
{
$title = _t(
- __CLASS__ . '.TITLE',
+ self::class . '.TITLE',
"Batch subscribe emails to Mailchimp"
);
$title .= " (limit:{$this->limit})";
- $title .= ($this->report_only ? " - report only" : "");
- return $title;
+ return $title . ($this->report_only ? " - report only" : "");
}
+ #[\Override]
public function getJobType()
{
return QueuedJob::QUEUED;
}
+ #[\Override]
public function setup()
{
$this->totalSteps = 1;
}
- private function getTotalResults($results)
+ private function getTotalResults(array $results): int|float
{
$total = 0;
- foreach ($results as $key => $count) {
+ foreach ($results as $count) {
$total += $count;
}
+
return $total;
}
- private function getTotalNonFailedResults($results)
+ private function getTotalNonFailedResults(array $results)
{
$copy = $results;
unset($copy[ MailchimpSubscriber::CHIMPLE_STATUS_FAIL]);
@@ -63,29 +67,35 @@ private function getTotalNonFailedResults($results)
/**
* Process the job
*/
+ #[\Override]
public function process()
{
$results = MailchimpSubscriber::batch_subscribe($this->limit, $this->report_only);
if ($this->report_only) {
$this->addMessage("Report only: " . json_encode($results));
- $this->totalSteps = $this->currentStep = $this->getTotalResults($results);
+ $this->totalSteps = $this->getTotalResults($results);
+ $this->currentStep = $this->totalSteps;
} elseif (is_array($results)) {
foreach ($results as $status => $count) {
$message = $status . ":" . $count;
$this->addMessage($message);
}
+
$this->totalSteps = $this->getTotalResults($results);// total including failed
$this->currentStep = $this->getTotalNonFailedResults($results);
} else {
$this->addMessage("Failed completely - check logs!");
- $this->totalSteps = $this->currentStep = 0;
+ $this->totalSteps = 0;
+ $this->currentStep = 0;
}
+
$this->isComplete = true;
}
/**
* Recreate the MailchimpSubscribeJob job for the next run
*/
+ #[\Override]
public function afterComplete()
{
$run_datetime = new DateTime();
@@ -94,6 +104,7 @@ public function afterComplete()
// min every 30s
$seconds = 30;
}
+
$run_datetime->modify("+{$seconds} seconds");
singleton(QueuedJobService::class)->queueJob(
new MailchimpSubscribeJob($this->limit, $this->report_only),
diff --git a/src/Models/Elements/ElementChimpleSubscribe.php b/src/Models/Elements/ElementChimpleSubscribe.php
index 17fbe4b..10744b5 100644
--- a/src/Models/Elements/ElementChimpleSubscribe.php
+++ b/src/Models/Elements/ElementChimpleSubscribe.php
@@ -24,45 +24,48 @@
*/
class ElementChimpleSubscribe extends BaseElement
{
- private static $table_name = 'ElementChimpleSubscribe';
+ private static string $table_name = 'ElementChimpleSubscribe';
- private static $singular_name = 'Mailchimp subscribe';
- private static $plural_name = 'Mailchimp subscribe';
+ private static string $singular_name = 'Mailchimp subscribe';
- private static $icon = 'font-icon-up-circled';
+ private static string $plural_name = 'Mailchimp subscribe';
- private static $db = [
+ private static string $icon = 'font-icon-up-circled';
+
+ private static array $db = [
'UseXHR' => 'Boolean',// whether to submit without redirect
'BeforeFormContent' => 'HTMLText',
'AfterFormContent' => 'HTMLText',
'ImageAlignment' => 'Varchar(32)',
];
- private static $defaults = [
+ private static array $defaults = [
'UseXHR' => 1
];
/**
* Has_one relationship
- * @var array
*/
- private static $has_one = [
+ private static array $has_one = [
'MailchimpConfig' => MailchimpConfig::class,
'Image' => Image::class
];
- private static $owns = [
+ private static array $owns = [
'Image'
];
+ #[\Override]
public function getType()
{
- return _t(__CLASS__ . '.BlockType', 'Mailchimp Subscribe');
+ return _t(self::class . '.BlockType', 'Mailchimp Subscribe');
}
- private static $title = 'Mailchimp subscribe';
- private static $description = 'Provide a mailchimp subscription form';
+ private static string $title = 'Mailchimp subscribe';
+
+ private static string $description = 'Provide a mailchimp subscription form';
+ #[\Override]
public function getCMSFields()
{
$fields = parent::getCMSFields();
@@ -74,7 +77,7 @@ public function getCMSFields()
LiteralField::create(
'NotEnabled',
''
- . _t(__CLASS__ . 'NOT_ENABLED', 'Mailchimp is not enable in site configuration')
+ . _t(self::class . 'NOT_ENABLED', 'Mailchimp is not enable in site configuration')
. '
'
)
);
@@ -90,7 +93,7 @@ public function getCMSFields()
DropdownField::create(
'MailchimpConfigID',
_t(
- __CLASS__ . '.SELECT_CONFIGURATION',
+ self::class . '.SELECT_CONFIGURATION',
'Select the list configuration to use for this subscription form'
),
MailchimpConfig::get()->sort('Title ASC')->map('ID', 'TitleWithDetails')
@@ -98,30 +101,30 @@ public function getCMSFields()
CheckboxField::create(
'UseXHR',
_t(
- __CLASS__ . '.USE_XHR',
+ self::class . '.USE_XHR',
'Submit without redirecting'
),
),
HTMLEditorField::create(
'BeforeFormContent',
_t(
- __CLASS__ . '.BEFORE_CONTENT',
+ self::class . '.BEFORE_CONTENT',
'Content to show before form'
)
)->setRows(6),
HTMLEditorField::create(
'AfterFormContent',
_t(
- __CLASS__ . '.AFTER_CONTENT',
+ self::class . '.AFTER_CONTENT',
'Content to show after form'
)
)->setRows(6),
UploadField::create(
'Image',
- _t(__CLASS__ . '.IMAGE', 'Image')
+ _t(self::class . '.IMAGE', 'Image')
)->setTitle(
_t(
- __CLASS__ . '.ADD_IMAGE_TO_CONTENT_BLOCK',
+ self::class . '.ADD_IMAGE_TO_CONTENT_BLOCK',
'Add an image'
)
)->setFolderName('blocks/content/' . $this->owner->ID)
@@ -129,14 +132,14 @@ public function getCMSFields()
->setIsMultiUpload(false),
DropdownField::create(
'ImageAlignment',
- _t(__CLASS__ . '.IMAGE_ALIGNMENT', 'Image alignment'),
+ _t(self::class . '.IMAGE_ALIGNMENT', 'Image alignment'),
[
- 'left' => _t(__CLASS__ . '.LEFT', 'Left'),
- 'right' => _t(__CLASS__ . '.RIGHT', 'Right')
+ 'left' => _t(self::class . '.LEFT', 'Left'),
+ 'right' => _t(self::class . '.RIGHT', 'Right')
]
)->setEmptyString('Choose an option')
->setDescription(
- _t(__CLASS__ . '.IMAGE_ALIGNMENT_DESCRIPTION', 'Use of this option is dependent on the theme')
+ _t(self::class . '.IMAGE_ALIGNMENT_DESCRIPTION', 'Use of this option is dependent on the theme')
)
]
);
@@ -160,6 +163,7 @@ public function getSubscribeForm(): ?SubscribeForm
$form = $config->SubscribeForm($this->UseXHR == 1);
return $form;
}
+
return null;
}
}
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index 7c0926d..6c34b78 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -31,25 +31,28 @@
*/
class MailchimpConfig extends DataObject implements TemplateGlobalProvider, PermissionProvider
{
- private static $list_id = "";// default list (audience) ID
- private static $api_key = "";// API key provided by Mailchimp
+ private static string $list_id = "";
+ // default list (audience) ID
+ private static string $api_key = "";// API key provided by Mailchimp
- private static $success_message = "Thank you for subscribing. You will receive an email to confirm your subscription shortly.";
- private static $error_message = "Sorry, we could not subscribe that email address at the current time. Please try again later.";
+ private static string $success_message = "Thank you for subscribing. You will receive an email to confirm your subscription shortly.";
- private static $table_name = 'ChimpleConfig';
+ private static string $error_message = "Sorry, we could not subscribe that email address at the current time. Please try again later.";
- private static $singular_name = 'Mailchimp Configuration';
- private static $plural_name = 'Mailchimp Configurations';
+ private static string $table_name = 'ChimpleConfig';
- private static $title = "Mailchimp Subscriber Form";
- private static $description = "Configuration for a Mailchimp subscribe form";
+ private static string $singular_name = 'Mailchimp Configuration';
+
+ private static string $plural_name = 'Mailchimp Configurations';
+
+ private static string $title = "Mailchimp Subscriber Form";
+
+ private static string $description = "Configuration for a Mailchimp subscribe form";
/**
* Database fields
- * @var array
*/
- private static $db = [
+ private static array $db = [
'Title' => 'Varchar(255)',
'Code' => 'Varchar(255)',// auto created, used to identify config
'IsGlobal' => 'Boolean',
@@ -70,9 +73,8 @@ class MailchimpConfig extends DataObject implements TemplateGlobalProvider, Perm
/**
* Defines summary fields commonly used in table columns
* as a quick overview of the data for this dataobject
- * @var array
*/
- private static $summary_fields = [
+ private static array $summary_fields = [
'Title' => 'Title',
'Code' => 'Code',
'IsGlobal.Nice' => 'Default',
@@ -81,16 +83,15 @@ class MailchimpConfig extends DataObject implements TemplateGlobalProvider, Perm
'UseXHR.Nice' => 'Submit w/o redirect'
];
- private static $indexes = [
+ private static array $indexes = [
'MailchimpListId' => true,
'Code' => ['type' => 'unique']
];
/**
* Add default values to database
- * @var array
*/
- private static $defaults = [
+ private static array $defaults = [
'UpdateExisting' => 1,// @deprecated
'SendWelcome' => 0,// @deprecated
'ReplaceInterests' => 0,// @deprecated
@@ -99,12 +100,12 @@ class MailchimpConfig extends DataObject implements TemplateGlobalProvider, Perm
'UseXHR' => 1
];
- public function TitleCode()
+ public function TitleCode(): string
{
return "{$this->Title} ({$this->Code})";
}
- public static function isEnabled()
+ public static function isEnabled(): bool
{
$site_config = SiteConfig::current_site_config();
return $site_config->MailchimpEnabled == 1;
@@ -125,34 +126,35 @@ public static function getApiKey()
*/
public static function getDataCentre(): string
{
- $dc = '';
$key = self::getApiKey();
$parts = [];
if($key) {
- $parts = explode("-", $key);
+ $parts = explode("-", (string) $key);
}
- return !empty($parts[1]) ? $parts[1] : '';
+
+ return empty($parts[1]) ? '' : $parts[1];
}
- public function TitleWithCode()
+ public function TitleWithCode(): string
{
return $this->Title . " - (code {$this->Code})";
}
- public function TitleWithDetails()
+ public function TitleWithDetails(): string
{
$title = $this->Title;
$list_id = $this->getMailchimpListId();
- $title .= " (list {$list_id})";
- return $title;
+ return $title . " (list {$list_id})";
}
+ #[\Override]
public function onBeforeWrite()
{
parent::onBeforeWrite();
if (!$this->Code) {
$this->Code = bin2hex(random_bytes(16));
}
+
$this->Code = Convert::raw2url($this->Code);
if($this->IsGlobal == 1) {
@@ -183,10 +185,11 @@ public function getMailchimpListId(): ?string
if (!$list_id) {
$list_id = self::getDefaultMailchimpListId();
}
+
return $list_id;
}
- public function HasMailchimpListId()
+ public function HasMailchimpListId(): bool
{
return $this->getMailchimpListId() != '';
}
@@ -196,18 +199,22 @@ public static function getConfig($id = '', $list_id = '', $code = ''): ?self
if ($id) {
return MailchimpConfig::get()->byId($id);
}
+
if ($list_id) {
return MailchimpConfig::get()->filter('MailchimpListId', $list_id)->first();
}
+
if ($code) {
return MailchimpConfig::get()->filter('Code', $code)->first();
}
+
return null;
}
/**
* @inheritdoc
*/
+ #[\Override]
public function getCMSFields()
{
$fields = parent::getCMSFields();
@@ -228,7 +235,7 @@ public function getCMSFields()
'NoApiKey',
''
. _t(
- __CLASS__ . '.NO_API_KEY',
+ self::class . '.NO_API_KEY',
'Warning: no API key was found in the system configuration - subscriptions cannot occur until this is set.'
)
. '
'
@@ -242,7 +249,7 @@ public function getCMSFields()
TextField::create(
'ArchiveLink',
_t(
- __CLASS__ . '.ARCHIVE_URL',
+ self::class . '.ARCHIVE_URL',
'Newsletter archive URL'
)
)
@@ -252,14 +259,14 @@ public function getCMSFields()
$list_id = $this->getField('MailchimpListId');
$fields->dataFieldByName('MailchimpListId')
->setDescription(
- !$list_id ?
- sprintf(
+ $list_id ?
+ "" : sprintf(
_t(
- __CLASS__ . '.NO_LIST_ID',
+ self::class . '.NO_LIST_ID',
"No list Id is set, the default list id '%s' is being used."
),
$default_list_id
- ) : ""
+ )
);
// this is set from SiteConfig
@@ -270,7 +277,7 @@ public function getCMSFields()
'IsGlobalBanner',
''
. _t(
- __CLASS__. '.CONFIG_IS_GLOBAL',
+ self::class. '.CONFIG_IS_GLOBAL',
'This configuration is the default for this website'
)
. '
'
@@ -284,7 +291,7 @@ public function getCMSFields()
MultiValueTextField::create(
'Tags',
_t(
- __CLASS__ . '.TAGS_FOR_SUBSCRIPTIONS',
+ self::class . '.TAGS_FOR_SUBSCRIPTIONS',
'Tags assigned to subscribers'
)
)
@@ -295,7 +302,7 @@ public function getCMSFields()
CheckboxField::create(
'UseXHR',
_t(
- __CLASS__ . '.USE_XHR',
+ self::class . '.USE_XHR',
'Submit without redirecting'
)
),
@@ -308,14 +315,14 @@ public function getCMSFields()
HTMLEditorField::create(
'BeforeFormContent',
_t(
- __CLASS__ . '.BEFORE_CONTENT',
+ self::class . '.BEFORE_CONTENT',
'Content to show before form'
)
)->setRows(6),
HTMLEditorField::create(
'AfterFormContent',
_t(
- __CLASS__ . '.AFTER_CONTENT',
+ self::class . '.AFTER_CONTENT',
'Content to show after form'
)
)->setRows(6)
@@ -324,7 +331,7 @@ public function getCMSFields()
if($heading = $fields->dataFieldByName('Heading')) {
$heading->setDescription(_t(
- __CLASS__ . '.HEADING_DESCRIPTON',
+ self::class . '.HEADING_DESCRIPTON',
'Displayed above the form'
));
}
@@ -344,13 +351,14 @@ public function MailchimpLink(): string
/**
* Ensure the subscription for the global footer is added
*/
+ #[\Override]
public function requireDefaultRecords()
{
$config = MailchimpConfig::get()->filter(['IsGlobal' => 1])->first();
if (empty($config->ID)) {
$config = MailchimpConfig::create([
- 'Title' => _t(__CLASS__ . '.DEFAULT_CONFIG_TITLE', 'Default Configuration'),
- 'Heading' => _t(__CLASS__ . '.DEFAULT_CONFIG_HEADER', 'Subscribe'),
+ 'Title' => _t(self::class . '.DEFAULT_CONFIG_TITLE', 'Default Configuration'),
+ 'Heading' => _t(self::class . '.DEFAULT_CONFIG_HEADER', 'Subscribe'),
'IsGlobal' => 1,
'MailchimpListId' => null
]);
@@ -359,6 +367,7 @@ public function requireDefaultRecords()
} else {
$config_id = $config->ID;
}
+
if ($config_id) {
$site_config = SiteConfig::current_site_config();
if (!empty($site_config->ID) && empty($site_config->MailchimpConfigID)) {
@@ -401,6 +410,7 @@ public function SubscribeForm($force_xhr = null): ?SubscribeForm
if ($this->Heading) {
$form->setLegend($this->Heading);
}
+
$form->addExtraClass('form-subscribe');
return $form;
}
@@ -414,34 +424,39 @@ public function SubscribeForm($force_xhr = null): ?SubscribeForm
public function Alerts(): string
{
return ''
- . _t(__CLASS__ . '.SUBSCRIBE_SUCCESS', htmlspecialchars($this->config()->get('success_message')))
+ . _t(self::class . '.SUBSCRIBE_SUCCESS', htmlspecialchars((string) $this->config()->get('success_message')))
. '
'
. ''
- . _t(__CLASS__ . '.SUBSCRIBE_ERROR', htmlspecialchars($this->config()->get('error_message')))
+ . _t(self::class . '.SUBSCRIBE_ERROR', htmlspecialchars((string) $this->config()->get('error_message')))
. '
'
. '';// info added by JS
}
+ #[\Override]
public function canView($member = null)
{
return Permission::checkMember($member, 'MAILCHIMP_CONFIG_VIEW');
}
+ #[\Override]
public function canCreate($member = null, $context = [])
{
return Permission::checkMember($member, 'MAILCHIMP_CONFIG_CREATE');
}
+ #[\Override]
public function canEdit($member = null)
{
return Permission::checkMember($member, 'MAILCHIMP_CONFIG_EDIT');
}
+ #[\Override]
public function canDelete($member = null)
{
return Permission::checkMember($member, 'MAILCHIMP_CONFIG_DELETE');
}
+ #[\Override]
public function providePermissions()
{
return [
@@ -470,9 +485,10 @@ public function providePermissions()
public function forTemplate($force_xhr = null): ?DBHTMLText
{
$form = $this->SubscribeForm($force_xhr);
- if($form) {
+ if($form instanceof \NSWDPC\Chimple\Forms\SubscribeForm) {
return $this->customise(['Form' => $form])->renderWith(self::class);
}
+
return null;
}
@@ -485,10 +501,10 @@ public function forTemplate($force_xhr = null): ?DBHTMLText
*/
public static function get_chimple_subscribe_form(...$args): ?DBHTMLText
{
- $code = isset($args[0]) ? $args[0] : '';
+ $code = $args[0] ?? '';
if ($code) {
$config = self::getConfig('', '', $code);
- if ($config) {
+ if ($config instanceof \NSWDPC\Chimple\Models\MailchimpConfig) {
// default to let the config decide
$force_xhr = null;
if(isset($args[1])) {
@@ -500,9 +516,11 @@ public static function get_chimple_subscribe_form(...$args): ?DBHTMLText
$force_xhr = true;
}
}
+
return $config->forTemplate($force_xhr);
}
}
+
return null;
}
@@ -516,9 +534,11 @@ public static function get_chimple_global_subscribe_form(): ?DBHTMLText
if ($config) {
return $config->forTemplate();
}
+
return null;
}
+ #[\Override]
public static function get_template_global_variables()
{
return [
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index e3bdeaf..171b374 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -19,71 +19,69 @@
class MailchimpSubscriber extends DataObject implements PermissionProvider
{
public const CHIMPLE_STATUS_UNKNOWN = '';
+
public const CHIMPLE_STATUS_NEW = 'NEW';
+
public const CHIMPLE_STATUS_PROCESSING = 'PROCESSING';
+
public const CHIMPLE_STATUS_BATCHED = 'BATCHED';
+
public const CHIMPLE_STATUS_SUCCESS = 'SUCCESS';
+
public const CHIMPLE_STATUS_FAIL = 'FAIL';
public const MAILCHIMP_SUBSCRIBER_PENDING = 'pending';
+
public const MAILCHIMP_SUBSCRIBER_SUBSCRIBED = 'subscribed';
+
public const MAILCHIMP_SUBSCRIBER_UNSUBSCRIBED = 'unsubscribed';
+
public const MAILCHIMP_SUBSCRIBER_CLEANED = 'cleaned';
public const MAILCHIMP_TAG_INACTIVE = 'inactive';
+
public const MAILCHIMP_TAG_ACTIVE = 'active';
public const MAILCHIMP_EMAIL_TYPE_HTML = 'html';
+
public const MAILCHIMP_EMAIL_TYPE_TEXT = 'text';
- /**
- * @var string
- */
- private static $table_name = 'ChimpleSubscriber';
+ private static string $table_name = 'ChimpleSubscriber';
/**
* Singular name for CMS
- * @var string
*/
- private static $singular_name = 'Mailchimp Subscriber';
+ private static string $singular_name = 'Mailchimp Subscriber';
/**
* Plural name for CMS
- * @var string
*/
- private static $plural_name = 'Mailchimp Subscribers';
+ private static string $plural_name = 'Mailchimp Subscribers';
/**
* Default sort ordering
- * @var array
*/
- private static $default_sort = ['Created' => 'DESC'];
+ private static array $default_sort = ['Created' => 'DESC'];
/**
* Default chr for obfuscation
- * @var string
*/
- private static $obfuscation_chr = "•";
+ private static string $obfuscation_chr = "•";
/**
* Email type, defaults to 'html', other value is 'text'
- * @var string
*/
- private static $email_type = self::MAILCHIMP_EMAIL_TYPE_HTML;
+ private static string $email_type = self::MAILCHIMP_EMAIL_TYPE_HTML;
/**
* Remove tags that do not exist in the tags list when a subscriber
* attempts to update their subscription
* This is a potentially destructive action as it will remove tags added to
* a subscriber via other means
- * @var bool
*/
- private static $remove_subscriber_tags = false;
+ private static bool $remove_subscriber_tags = false;
- /**
- * @var array
- */
- private static $db = [
+ private static array $db = [
'Name' => 'Varchar(255)',
'Surname' => 'Varchar(255)',
'Email' => 'Varchar(255)',
@@ -107,12 +105,12 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
'Tags' => 'MultiValueField'
];
- private static $sync_fields = [
+ private static array $sync_fields = [
'Name' => 'FNAME',
'Surname' => 'LNAME'
];
- private static $indexes = [
+ private static array $indexes = [
'Status' => true,
'Email' => true,
'Name' => true,
@@ -123,9 +121,8 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
/**
* Add default values to database
- * @var array
*/
- private static $defaults = [
+ private static array $defaults = [
'Status' => self::CHIMPLE_STATUS_NEW,
'UpdateExisting' => 1,// @deprecated
'SendWelcome' => 0,// @deprecated
@@ -136,9 +133,8 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
/**
* Defines summary fields commonly used in table columns
* as a quick overview of the data for this dataobject
- * @var array
*/
- private static $summary_fields = [
+ private static array $summary_fields = [
'Created.Nice' => 'Created',
'Name' => 'Name',
'Surname' => 'Surname',
@@ -151,9 +147,8 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
/**
* Defines a default list of filters for the search context
- * @var array
*/
- private static $searchable_fields = [
+ private static array $searchable_fields = [
'Name' => 'PartialMatchFilter',
'Surname' => 'PartialMatchFilter',
'Email' => 'PartialMatchFilter',
@@ -165,25 +160,26 @@ class MailchimpSubscriber extends DataObject implements PermissionProvider
* @var MailchimpApiClient
* The Mailchimp API client instance
*/
- protected static $mailchimp = null;
+ protected static $mailchimp;
/**
* List of current subscriber tags
- * @var array|null
*/
- private $_cache_tags = null;
+ private ?array $_cache_tags = null;
/**
* Return whether subscription was success
*/
- public function getSuccessful()
+ public function getSuccessful(): bool
{
return $this->Status == self::CHIMPLE_STATUS_SUCCESS;
}
+
/**
* @inheritdoc
*/
+ #[\Override]
public function getCMSFields()
{
$fields = parent::getCMSFields();
@@ -204,7 +200,7 @@ public function getCMSFields()
$fields->dataFieldByName('LastError')
->setDescription(
_t(
- __CLASS__. '.IF_ERROR_OCCURRED',
+ self::class. '.IF_ERROR_OCCURRED',
"If a subscription error occurred, this will display the last error returned by Mailchimp and can help determine the cause of the error"
)
)
@@ -214,13 +210,13 @@ public function getCMSFields()
if($this->exists()) {
$status_field = DropdownField::create(
'Status',
- _t(__CLASS__ . '.STATUS', 'Status'),
+ _t(self::class . '.STATUS', 'Status'),
[
self::CHIMPLE_STATUS_UNKNOWN => '',
- self::CHIMPLE_STATUS_NEW => _t(__CLASS__ . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
- self::CHIMPLE_STATUS_PROCESSING => _t(__CLASS__ . '.STATUS_PROCESSING', 'PROCESSING (the subscriber is in the process of being subscribed)'),
- self::CHIMPLE_STATUS_SUCCESS => _t(__CLASS__ . '.STATUS_SUCCESS', 'SUCCESS (the subscriber was subscribed)'),
- self::CHIMPLE_STATUS_FAIL => _t(__CLASS__ . '.STATUS_FAIL', 'FAIL (the subscriber could not be subscribed - check the \'Last Error\' value)')
+ self::CHIMPLE_STATUS_NEW => _t(self::class . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
+ self::CHIMPLE_STATUS_PROCESSING => _t(self::class . '.STATUS_PROCESSING', 'PROCESSING (the subscriber is in the process of being subscribed)'),
+ self::CHIMPLE_STATUS_SUCCESS => _t(self::class . '.STATUS_SUCCESS', 'SUCCESS (the subscriber was subscribed)'),
+ self::CHIMPLE_STATUS_FAIL => _t(self::class . '.STATUS_FAIL', "FAIL (the subscriber could not be subscribed - check the 'Last Error' value)")
]
);
@@ -234,27 +230,27 @@ public function getCMSFields()
// stuck processing - can reset to new
$status_field->setDescription(
_t(
- __CLASS__ . '.PROCESSING_RESET_NEW_STATUS',
+ self::class . '.PROCESSING_RESET_NEW_STATUS',
"If this attempt is stuck, reset to 'New' for another attempt"
)
);
// can retain failed or set to new for retry
$status_field->setSource([
- self::CHIMPLE_STATUS_NEW => _t(__CLASS__ . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
- self::CHIMPLE_STATUS_PROCESSING => _t(__CLASS__ . '.STATUS_PROCESSING', 'PROCESSING (the subscriber is in the process of being subscribed)'),
+ self::CHIMPLE_STATUS_NEW => _t(self::class . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
+ self::CHIMPLE_STATUS_PROCESSING => _t(self::class . '.STATUS_PROCESSING', 'PROCESSING (the subscriber is in the process of being subscribed)'),
]);
} elseif($this->Status == self::CHIMPLE_STATUS_FAIL) {
// handling when failed
$status_field->setDescription(
_t(
- __CLASS__ . '.FAIL_RESET_NEW_STATUS',
+ self::class . '.FAIL_RESET_NEW_STATUS',
"Reset this value to 'New' to retry a failed subscription attempt"
)
);
// can retain failed or set to new for retry
$status_field->setSource([
- self::CHIMPLE_STATUS_NEW => _t(__CLASS__ . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
- self::CHIMPLE_STATUS_FAIL => _t(__CLASS__ . '.STATUS_FAIL', 'FAIL (the subscriber could not be subscribed - check the \'Last Error\' value)')
+ self::CHIMPLE_STATUS_NEW => _t(self::class . '.STATUS_NEW', 'NEW (the subscriber has not yet been subscribed)'),
+ self::CHIMPLE_STATUS_FAIL => _t(self::class . '.STATUS_FAIL', "FAIL (the subscriber could not be subscribed - check the 'Last Error' value)")
]);
}
@@ -275,8 +271,8 @@ public function getCMSFields()
'StatusForNew',
''
. _t(
- __CLASS__ . '.STATUS_NEW_MESSAGE',
- 'This subscription attempt record will be given status of \'New\' and it will enter the pending subscription queue upon save'
+ self::class . '.STATUS_NEW_MESSAGE',
+ "This subscription attempt record will be given status of 'New' and it will enter the pending subscription queue upon save"
)
. '
'
),
@@ -286,9 +282,9 @@ public function getCMSFields()
$tags = $this->getCurrentSubscriberTags();
$tag_field_description = "";
- if(!empty($tags)) {
+ if($tags !== []) {
$tag_field_description = _t(
- __CLASS__ . '.TAGS_FIELD_DESCRIPTION',
+ self::class . '.TAGS_FIELD_DESCRIPTION',
'The current tags for this subscriber are {tags}
Tags not in the tag update list will be removed. New tags will be added.',
[
'tags' => implode(", ", $tags)
@@ -302,19 +298,19 @@ public function getCMSFields()
KeyValueField::create(
'MergeFields',
_t(
- __CLASS__ . '.MERGE_FIELDS',
+ self::class . '.MERGE_FIELDS',
'Merge fields for this subscription attempt'
)
)->setDescription(
_t(
- __CLASS__ . '.MERGE_FIELDS_DESCRIPTION',
+ self::class . '.MERGE_FIELDS_DESCRIPTION',
'Keys are merge tag names, values are the values for this particular subscriber'
)
),
MultiValueTextField::create(
'Tags',
_t(
- __CLASS__ . '.TAGS_FIELD',
+ self::class . '.TAGS_FIELD',
'Tag update list'
)
)->setDescription(
@@ -332,10 +328,10 @@ public function getCMSFields()
}
$readonly_fields = [
- 'MailchimpListId' => _t(__CLASS__ . '.SUBSCRIBER_LIST_ID', "The Mailchimp List (audience) Id for this subscription record"),
- 'SubscribedUniqueEmailId' => _t(__CLASS__ . '.SUBSCRIBER_UNIQUE_EMAIL_ID', "An identifier for the address across all of Mailchimp."),
- 'SubscribedWebId' => _t(__CLASS__ . '.SUBSCRIBER_WEB_ID', "Member profile page: {link}", ['link' => $subscriber_profile_link]),
- 'SubscribedId' => _t(__CLASS__ . '.SUBSCRIBER_ID', "The MD5 hash of the lowercase version of the list member's email address.")
+ 'MailchimpListId' => _t(self::class . '.SUBSCRIBER_LIST_ID', "The Mailchimp List (audience) Id for this subscription record"),
+ 'SubscribedUniqueEmailId' => _t(self::class . '.SUBSCRIBER_UNIQUE_EMAIL_ID', "An identifier for the address across all of Mailchimp."),
+ 'SubscribedWebId' => _t(self::class . '.SUBSCRIBER_WEB_ID', "Member profile page: {link}", ['link' => $subscriber_profile_link]),
+ 'SubscribedId' => _t(self::class . '.SUBSCRIBER_ID', "The MD5 hash of the lowercase version of the list member's email address.")
];
foreach($readonly_fields as $readonly_field => $description) {
@@ -345,6 +341,7 @@ public function getCMSFields()
if($description) {
$field->setDescription($description);
}
+
$fields->addFieldToTab(
'Root.Main',
$field
@@ -355,6 +352,7 @@ public function getCMSFields()
return $fields;
}
+ #[\Override]
public function onBeforeWrite()
{
parent::onBeforeWrite();
@@ -368,7 +366,7 @@ public function onBeforeWrite()
$this->Surname = $this->getSurnameFromName();
// reset name
$parts = explode(" ", $this->Name, 2);
- $this->Name = isset($parts[0]) ? $parts[0] : '';
+ $this->Name = $parts[0] ?? '';
}
}
@@ -377,11 +375,10 @@ public function onBeforeWrite()
* Given some meta data, update the MergeFields for this subscriber
* The parameter can contain values submitted via a form
* By default MergeFields doesn't allow HTML tags as keys or as values
- * @param array $meta
*/
public function updateMergeFields(array $meta)
{
- if(empty($meta)) {
+ if($meta === []) {
return;
}
@@ -391,15 +388,17 @@ public function updateMergeFields(array $meta)
// ignore values that cannot be saved
continue;
}
+
$key = strtoupper(trim(strip_tags($k)));
$value = trim(strip_tags($v));
$data[ $key ] = $value;
}
+
$this->MergeFields = $data;
$this->write();
}
- public function HasLastError()
+ public function HasLastError(): string
{
return trim($this->LastError ?? '') !== '' ? "yes" : "no";
}
@@ -407,12 +406,13 @@ public function HasLastError()
/**
* Attempt to get a surname from the name
*/
- public function getSurnameFromName()
+ public function getSurnameFromName(): ?string
{
$parts = explode(" ", $this->Name, 2);
- if (!empty($parts[1])) {
+ if (isset($parts[1]) && ($parts[1] !== '' && $parts[1] !== '0')) {
return $parts[1];
}
+ return null;
}
/**
@@ -424,10 +424,12 @@ public static function api(): MailchimpApiClient
if(self::$mailchimp instanceof MailchimpApiClient) {
return self::$mailchimp;
}
+
$api_key = MailchimpConfig::getApiKey();
if (!$api_key) {
throw new Exception("No Mailchimp API Key configured!");
}
+
self::$mailchimp = new MailchimpApiClient($api_key);
return self::$mailchimp;
}
@@ -435,7 +437,7 @@ public static function api(): MailchimpApiClient
/**
* @deprecated use self::api() instead
*/
- public function getMailchimp()
+ public function getMailchimp(): \DrewM\MailChimp\MailChimp
{
return self::api();
}
@@ -449,6 +451,7 @@ public function getMailchimpListId()
if (!$list_id) {
$list_id = MailchimpConfig::getDefaultMailchimpListId();
}
+
return $list_id;
}
@@ -461,14 +464,15 @@ protected function applyMergeFields(): array
// get subscriber meta data
$meta = $this->MergeFields->getValue();
- if(is_array($meta) && !empty($meta)) {
+ if(is_array($meta) && $meta !== []) {
foreach($meta as $k => $v) {
if($v === '') {
// do not set empty values, MailChimp does not like this
continue;
}
+
$k = strtoupper(trim($k));
- $merge_fields[$k] = trim($v);
+ $merge_fields[$k] = trim((string) $v);
}
}
@@ -480,18 +484,17 @@ protected function applyMergeFields(): array
// ignore non-existent fields
continue;
}
+
$value = $this->getField($field);
- if(!is_string($value)) {
- $value = '';
- } else {
- $value = trim($value);
- }
+ $value = is_string($value) ? trim($value) : '';
+
if ($value === '') {
// do not set empty values, MailChimp does not like this
// "The resource submitted could not be validated"
continue;
}
- $tag = strtoupper(trim($tag));
+
+ $tag = strtoupper(trim((string) $tag));
$merge_fields[$tag] = $value;
}
@@ -510,18 +513,17 @@ public function getSubscribeRecord(): array
if(!$email_type || $email_type != self::MAILCHIMP_EMAIL_TYPE_HTML || $email_type != self::MAILCHIMP_EMAIL_TYPE_TEXT) {
$email_type = self::MAILCHIMP_EMAIL_TYPE_HTML;
}
- $params = [
+ return [
'email_address' => $this->Email,
'email_type' => $email_type,
'merge_fields' => $merge_fields
];
- return $params;
}
/**
* Return tags for this subscriber
*/
- public function getSubscriberTags()
+ public function getSubscriberTags(): array
{
$tags = $this->Tags->getValue();
if(!is_array($tags)) {
@@ -541,17 +543,18 @@ private function obfuscate()
if($length == 0) {
return "";
}
+
$chr = $this->config()->get('obfuscation_chr');
if($chr === "") {
// if no chr configured, do not obfuscate (e.g not require by project)
return $in;
}
+
$sub_length = $length - 2;
if($sub_length <= 0) {
return str_repeat($chr, $length);
}
- $replaced = substr_replace($in, str_repeat($chr, $sub_length), 1, $sub_length);
- return $replaced;
+ return substr_replace($in, str_repeat($chr, $sub_length), 1, $sub_length);
};
$this->Email = $obfuscate($this->Email ?? '');
$this->Name = $obfuscate($this->Name ?? '');
@@ -563,7 +566,7 @@ private function obfuscate()
*/
public static function getMailchimpSubscribedId($email): string
{
- if(!is_string($email) || !$email) {
+ if(!is_string($email) || ($email === '' || $email === '0')) {
return '';
} else {
return MailchimpApiClient::subscriberHash($email);
@@ -580,26 +583,26 @@ public static function checkExistsInList(string $list_id, string $email, string
{
// sanity check on input
- if(!$email) {
+ if($email === '' || $email === '0') {
throw new \Exception(
_t(
- __CLASS__ . ".EMAIL_NOT_PROVIDED",
+ self::class . ".EMAIL_NOT_PROVIDED",
"Please provide an email address"
)
);
}
- if(!$list_id) {
+ if($list_id === '' || $list_id === '0') {
throw new \Exception(
_t(
- __CLASS__ . ".AUDIENCE_NOT_PROVIDED",
+ self::class . ".AUDIENCE_NOT_PROVIDED",
"Please provide a Mailchimp audience/list ID"
)
);
}
// attempt to get the subscriber
- if($hash = self::getMailchimpSubscribedId($email)) {
+ if(($hash = self::getMailchimpSubscribedId($email)) !== '' && ($hash = self::getMailchimpSubscribedId($email)) !== '0') {
$result = self::api()->get(
"lists/{$list_id}/members/{$hash}"
);
@@ -637,7 +640,7 @@ public function subscribe(): bool
$result = false;
- if(!$existing) {
+ if($existing === [] || $existing === false) {
$operation_path = "lists/{$list_id}/members";
$params = $this->getSubscribeRecord();
// add tags
@@ -675,16 +678,17 @@ public function subscribe(): bool
$this->write();
return true;
} elseif (!empty($result['status'])) {
- $error_detail = isset($result['detail']) ? $result['detail'] : '';
+ $error_detail = $result['detail'] ?? '';
$error_status = $result['status'];
$error_title = $result['title'];
$errors = "{$error_status}|{$error_title}|{$error_detail}";
} else {
$errors = "Unhandled error for email: {$this->Email}";
}
+
throw new Exception(trim($errors));
- } catch (Exception $e) {
- $last_error = $e->getMessage();
+ } catch (Exception $exception) {
+ $last_error = $exception->getMessage();
}
// record failure
@@ -714,7 +718,7 @@ private function getCurrentSubscriberTags(bool $force = false, int $count = 10):
$list_id = $this->MailchimpListId;
$subscriber_hash = self::getMailchimpSubscribedId($this->Email ?? '');
- if(!$list_id || !$subscriber_hash) {
+ if(!$list_id || ($subscriber_hash === '' || $subscriber_hash === '0')) {
$this->_cache_tags = null;
return [];
}
@@ -724,12 +728,12 @@ private function getCurrentSubscriberTags(bool $force = false, int $count = 10):
$operation_path = "lists/{$list_id}/members/{$subscriber_hash}/tags/?count={$count}&offset={$offset}";
$result = self::api()->get($operation_path);
- $total = isset($result['total_items']) ? $result['total_items'] : 0;
+ $total = $result['total_items'] ?? 0;
// initial set of tags
$tags = isset($result['tags']) && is_array($result['tags']) ? $result['tags'] : [];
// populate the list of tags
- $walker = function ($value, $key) use (&$list) {
+ $walker = function (array $value, $key) use (&$list): void {
$list[] = $value['name'];
};
array_walk($tags, $walker);
@@ -802,7 +806,7 @@ protected function modifySubscriberTags(): bool
$operation_path = "/lists/{$list_id}/members/{$subscriber_hash}/tags";
// submit payload to API
- $result = self::api()->post(
+ self::api()->post(
$operation_path,
$params
);
@@ -829,11 +833,13 @@ public static function batch_subscribe($limit = 100, $report_only = false): arra
if ($limit) {
$subscribers = $subscribers->limit($limit);
}
+
if ($report_only) {
$results[ self::CHIMPLE_STATUS_PROCESSING ] = $subscribers->count();
foreach ($subscribers as $subscriber) {
Logger::log("REPORT_ONLY: would subscribe #{$subscriber->ID} to list {$subscriber->MailchimpListId}", 'DEBUG');
}
+
return $results;
}
@@ -849,22 +855,26 @@ public static function batch_subscribe($limit = 100, $report_only = false): arra
// set status to 0
$results[ $subscriber->Status ] = 0;
}
+
// increment this status
$results[ $subscriber->Status ]++;
}
+
return $results;
- } catch (Exception $e) {
- Logger::log("FAIL: could not batch_subscribe, error=" . $e->getMessage(), 'NOTICE');
+ } catch (Exception $exception) {
+ Logger::log("FAIL: could not batch_subscribe, error=" . $exception->getMessage(), 'NOTICE');
}
return [];
}
+ #[\Override]
public function canView($member = null)
{
return Permission::checkMember($member, 'MAILCHIMP_SUBSCRIBER_VIEW');
}
+ #[\Override]
public function canEdit($member = null)
{
return Permission::checkMember($member, 'MAILCHIMP_SUBSCRIBER_EDIT');
@@ -873,29 +883,32 @@ public function canEdit($member = null)
/**
* Only admin can delete subscribers
*/
+ #[\Override]
public function canDelete($member = null)
{
return Permission::checkMember($member, 'ADMIN');
}
+ #[\Override]
public function canCreate($member = null, $context = [])
{
return Permission::checkMember($member, 'MAILCHIMP_SUBSCRIBER_CREATE');
}
+ #[\Override]
public function providePermissions()
{
return [
'MAILCHIMP_SUBSCRIBER_VIEW' => [
- 'name' => _t(__CLASS__ . '.MAILCHIMP_SUBSCRIBER_VIEW', 'View Mailchimp Subscribers'),
+ 'name' => _t(self::class . '.MAILCHIMP_SUBSCRIBER_VIEW', 'View Mailchimp Subscribers'),
'category' => 'Mailchimp',
],
'MAILCHIMP_SUBSCRIBER_EDIT' => [
- 'name' => _t(__CLASS__ . '.MAILCHIMP_SUBSCRIBER_EDIT', 'Edit Mailchimp Subscribers'),
+ 'name' => _t(self::class . '.MAILCHIMP_SUBSCRIBER_EDIT', 'Edit Mailchimp Subscribers'),
'category' => 'Mailchimp',
],
'MAILCHIMP_SUBSCRIBER_CREATE' => [
- 'name' => _t(__CLASS__ . '.MAILCHIMP_SUBSCRIBER_CREATE', 'Create Mailchimp Subscribers'),
+ 'name' => _t(self::class . '.MAILCHIMP_SUBSCRIBER_CREATE', 'Create Mailchimp Subscribers'),
'category' => 'Mailchimp',
]
];
diff --git a/tests/ChimpleConfigTest.php b/tests/ChimpleConfigTest.php
index e3b37b4..911535f 100644
--- a/tests/ChimpleConfigTest.php
+++ b/tests/ChimpleConfigTest.php
@@ -45,6 +45,7 @@ class ChimpleConfigTest extends SapphireTest
/**
* @inheritdoc
*/
+ #[\Override]
public function setUp(): void
{
parent::setUp();
@@ -71,7 +72,7 @@ public function setUp(): void
$config->write();
}
- protected function getMailchimpConfig()
+ protected function getMailchimpConfig(): ?\NSWDPC\Chimple\Models\MailchimpConfig
{
// get config for the test list
@@ -95,7 +96,7 @@ protected function getMailchimpConfig()
}
- public function testConfiguration()
+ public function testConfiguration(): void
{
$forceXhr = true;
@@ -115,7 +116,7 @@ public function testConfiguration()
$email = $fields->dataFieldByName('Email');
$this->assertTrue($email instanceof EmailField, "Email field is not an email field");
- $name = $fields->dataFieldByName('Name');
+ $fields->dataFieldByName('Name');
$this->assertTrue($email instanceof TextField, "Name field is not an text field");
$token_name = SecurityToken::get_default_name();
@@ -139,7 +140,7 @@ public function testConfiguration()
}
- public function testCanBeCached()
+ public function testCanBeCached(): void
{
Config::modify()->set(XhrSubscribeForm::class, 'disable_security_token', true);
@@ -168,7 +169,7 @@ public function testCanBeCached()
}
- public function testSubscribeFormTemplateVariable()
+ public function testSubscribeFormTemplateVariable(): void
{
$config = $this->getMailchimpConfig();
$config->UseXHR = 0;
@@ -176,34 +177,34 @@ public function testSubscribeFormTemplateVariable()
// Use config value
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, 'data-xhr="1"'), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, null);
- $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, 'data-xhr="1"'), "Attribute is in template");
// template override
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '1');
- $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, 'data-xhr="1"'), "Attribute is in template");
$config->UseXHR = 0;
$config->write();
$template = MailchimpConfig::get_chimple_subscribe_form($config->Code, '0');
- $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, 'data-xhr="1"'), "Attribute is not in template");
}
- public function testGlobalSubscribeFormTemplateVariable()
+ public function testGlobalSubscribeFormTemplateVariable(): void
{
$config = $this->getMailchimpConfig();
$config->UseXHR = 0;
$config->write();
// Use config value
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue(!str_contains($template, "data-xhr=\"1\""), "Attribute is not in template");
+ $this->assertTrue(!str_contains($template, 'data-xhr="1"'), "Attribute is not in template");
$config->UseXHR = 1;
$config->write();
$template = MailchimpConfig::get_chimple_global_subscribe_form();
- $this->assertTrue(str_contains($template, "data-xhr=\"1\""), "Attribute is in template");
+ $this->assertTrue(str_contains($template, 'data-xhr="1"'), "Attribute is in template");
}
}
diff --git a/tests/ChimpleFunctionalTest.php b/tests/ChimpleFunctionalTest.php
index 4792d85..75691f9 100644
--- a/tests/ChimpleFunctionalTest.php
+++ b/tests/ChimpleFunctionalTest.php
@@ -50,6 +50,7 @@ class ChimpleFunctionalTest extends FunctionalTest
protected $test_form_code = 'functionalformcode';
+ #[\Override]
public function setUp(): void
{
parent::setUp();
@@ -57,7 +58,7 @@ public function setUp(): void
// Inject test form
Injector::inst()->registerService(
- new TestSubscribeForm(),
+ \NSWDPC\Chimple\Tests\TestSubscribeForm::create(),
SubscribeForm::class
);
@@ -91,10 +92,10 @@ public function setUp(): void
$config->write();
}
- public function testFormSubmission()
+ public function testFormSubmission(): void
{
- $this->useTestTheme(__DIR__, 'chimpletest', function () {
+ $this->useTestTheme(__DIR__, 'chimpletest', function (): void {
// request default route
$url = "/mc-subscribe/v1/";
diff --git a/tests/ChimpleSubscriberTest.php b/tests/ChimpleSubscriberTest.php
index 9d8493a..d7b57b9 100644
--- a/tests/ChimpleSubscriberTest.php
+++ b/tests/ChimpleSubscriberTest.php
@@ -22,23 +22,20 @@ class ChimpleSubscriberTest extends SapphireTest
/**
* e.g example.com
- * @var string
*/
- private static $test_email_domain = "";
+ private static string $test_email_domain = "";
/**
* e.g bob.smith
- * @var string
*/
- private static $test_email_user = "";
+ private static string $test_email_user = "";
/**
* use plus notation in email address
- * @var bool
*/
- private static $test_use_plus = true;
+ private static bool $test_use_plus = true;
- public function testSubscriber()
+ public function testSubscriber(): void
{
$fname = "Test";
$lname = "Tester";
@@ -67,6 +64,7 @@ public function testSubscriber()
if($test_use_plus) {
$email_address_for_test .= "+unittest" . bin2hex(random_bytes(2));
}
+
$email_address_for_test .= "@{$test_email_domain}";
$tags = ['TestOne','TestTwo'];
@@ -99,7 +97,7 @@ public function testSubscriber()
$this->assertTrue(is_array($subscribe_record), "Record is not an array of values");
- $this->assertTrue(!empty($subscribe_record), "Record is empty");
+ $this->assertTrue($subscribe_record !== [], "Record is empty");
$this->assertTrue(isset($subscribe_record['merge_fields']), "Record merge_fields is not set");
@@ -126,11 +124,11 @@ public function testSubscriber()
$this->assertNotEmpty($subscriber->SubscribedUniqueEmailId, "SubscribedUniqueEmailId should not be empty");
- $this->assertTrue(substr_count($subscriber->Email, $obfuscation_chr) > 0, "Email is not obfuscated, it should be");
+ $this->assertTrue(substr_count($subscriber->Email, (string) $obfuscation_chr) > 0, "Email is not obfuscated, it should be");
- $this->assertTrue(substr_count($subscriber->Name, $obfuscation_chr) > 0, "Name is not obfuscated, it should be");
+ $this->assertTrue(substr_count($subscriber->Name, (string) $obfuscation_chr) > 0, "Name is not obfuscated, it should be");
- $this->assertTrue(substr_count($subscriber->Surname, $obfuscation_chr) > 0, "Surname is not obfuscated, it should be");
+ $this->assertTrue(substr_count($subscriber->Surname, (string) $obfuscation_chr) > 0, "Surname is not obfuscated, it should be");
$mc_record = MailchimpSubscriber::checkExistsInList($list_id, $email);
@@ -141,7 +139,7 @@ public function testSubscriber()
$this->assertEquals(count($tags), count($mc_record['tags']), "Tag count mismatch");
$mc_tags_list = [];
- array_walk($mc_record['tags'], function ($value, $key) use (&$mc_tags_list) {
+ array_walk($mc_record['tags'], function (array $value, $key) use (&$mc_tags_list): void {
$mc_tags_list[] = $value['name'];
});
diff --git a/tests/TestSubscribeForm.php b/tests/TestSubscribeForm.php
index b6b43d2..0222114 100644
--- a/tests/TestSubscribeForm.php
+++ b/tests/TestSubscribeForm.php
@@ -13,7 +13,7 @@ class TestSubscribeForm extends SubscribeForm implements TestOnly
/**
* No need to spam protection on tests
*/
- public function enableSpamProtection()
+ public function enableSpamProtection(): null
{
return null;
}
From a8e524f2e63bbcb476122c360a5b09fe7b89dccd Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Thu, 8 Aug 2024 03:12:14 +0000
Subject: [PATCH 27/41] [rector] Automated updates generated by rector
configuration
---
src/Controllers/ChimpleController.php | 14 ++++++--------
src/Jobs/MailchimpCleanupJob.php | 2 ++
src/Jobs/MailchimpSubscribeJob.php | 2 +-
src/Models/MailchimpConfig.php | 1 +
src/Models/MailchimpSubscriber.php | 3 +++
5 files changed, 13 insertions(+), 9 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 0a15284..324675a 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -108,9 +108,7 @@ public function setFormNameSuffix(string $suffix = ''): self
*/
public function getFormNameSuffix(): string
{
- $suffix = $this->formNameSuffix ? "_{$this->formNameSuffix}" : "";
-
- return $suffix;
+ return $this->formNameSuffix ? "_{$this->formNameSuffix}" : "";
}
/**
@@ -118,9 +116,7 @@ public function getFormNameSuffix(): string
*/
public function getSubscriptionForm($useXhr = false): SubscribeForm|XhrSubscribeForm|null
{
- $form = $useXhr ? $this->XhrSubscribeForm() : $this->SubscribeForm();
-
- return $form;
+ return $useXhr ? $this->XhrSubscribeForm() : $this->SubscribeForm();
}
/**
@@ -289,6 +285,7 @@ private function handleError($code, $error_message, Form $form = null): ?\Silver
// set session error on the form
$form->sessionError($error_message, ValidationResult::TYPE_ERROR);
}
+
return null;
}
@@ -304,6 +301,7 @@ private function handleSuccess(int $code, Form $form = null): ?\SilverStripe\Con
// set session message on the form
$form->sessionMessage($success_message, ValidationResult::TYPE_GOOD);
}
+
return null;
}
@@ -431,7 +429,7 @@ public function subscribe($data = [], Form $form = null)
// handle a successful subscription
$response = $this->handleSuccess(200, $form);
- if($response && ($response instanceof HTTPResponse)) {
+ if($response instanceof \SilverStripe\Control\HTTPResponse && ($response instanceof HTTPResponse)) {
// handle responses for e.g XHR
return $response;
} else {
@@ -454,7 +452,7 @@ public function subscribe($data = [], Form $form = null)
// Handle subscribe attempt failures
$response = $this->handleError($error_code, $error_message, $form);
- if($response && ($response instanceof HTTPResponse)) {
+ if($response instanceof \SilverStripe\Control\HTTPResponse && ($response instanceof HTTPResponse)) {
// handle XHR error responses
return $response;
} else {
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index ffa38b0..7d2e37b 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -93,6 +93,7 @@ private function processSubscriptions(): bool
$this->addMessage("Deleted {$success_deletes} subscribers with status " . MailchimpSubscriber::CHIMPLE_STATUS_SUCCESS);
}
+
$this->currentStep = $success_deletes;
$this->totalSteps = $success_deletes;
@@ -116,6 +117,7 @@ private function processSubscriptions(): bool
$this->addMessage("Deleted {$failed_deletes} subscribers with status " . MailchimpSubscriber::CHIMPLE_STATUS_FAIL);
}
+
$this->currentStep = $success_deletes + $failed_deletes;
$this->totalSteps = $success_deletes + $failed_deletes;
diff --git a/src/Jobs/MailchimpSubscribeJob.php b/src/Jobs/MailchimpSubscribeJob.php
index ca9c0b7..314eb05 100644
--- a/src/Jobs/MailchimpSubscribeJob.php
+++ b/src/Jobs/MailchimpSubscribeJob.php
@@ -57,7 +57,7 @@ private function getTotalResults(array $results): int|float
return $total;
}
- private function getTotalNonFailedResults(array $results)
+ private function getTotalNonFailedResults(array $results): int|float
{
$copy = $results;
unset($copy[ MailchimpSubscriber::CHIMPLE_STATUS_FAIL]);
diff --git a/src/Models/MailchimpConfig.php b/src/Models/MailchimpConfig.php
index 6c34b78..e5f6900 100644
--- a/src/Models/MailchimpConfig.php
+++ b/src/Models/MailchimpConfig.php
@@ -32,6 +32,7 @@
class MailchimpConfig extends DataObject implements TemplateGlobalProvider, PermissionProvider
{
private static string $list_id = "";
+
// default list (audience) ID
private static string $api_key = "";// API key provided by Mailchimp
diff --git a/src/Models/MailchimpSubscriber.php b/src/Models/MailchimpSubscriber.php
index 171b374..cf58b62 100644
--- a/src/Models/MailchimpSubscriber.php
+++ b/src/Models/MailchimpSubscriber.php
@@ -412,6 +412,7 @@ public function getSurnameFromName(): ?string
if (isset($parts[1]) && ($parts[1] !== '' && $parts[1] !== '0')) {
return $parts[1];
}
+
return null;
}
@@ -513,6 +514,7 @@ public function getSubscribeRecord(): array
if(!$email_type || $email_type != self::MAILCHIMP_EMAIL_TYPE_HTML || $email_type != self::MAILCHIMP_EMAIL_TYPE_TEXT) {
$email_type = self::MAILCHIMP_EMAIL_TYPE_HTML;
}
+
return [
'email_address' => $this->Email,
'email_type' => $email_type,
@@ -554,6 +556,7 @@ private function obfuscate()
if($sub_length <= 0) {
return str_repeat($chr, $length);
}
+
return substr_replace($in, str_repeat($chr, $sub_length), 1, $sub_length);
};
$this->Email = $obfuscate($this->Email ?? '');
From f9866f0d6f1056675d1fa59502eb299fea587a04 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:07:39 +1000
Subject: [PATCH 28/41] (ci) update naming of workflows
---
.github/workflows/ci.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 74b52b4..4d57913 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,8 +6,8 @@ on:
jobs:
Bundle:
name: 'Automated fixes'
- uses: nswdpc/ci-files/.github/workflows/bundle.yml@main
+ uses: nswdpc/ci-files/.github/workflows/silverstripe.yml@main
PHPStan:
name: 'PHPStan (analyse)'
- uses: nswdpc/ci-files/.github/workflows/phpstan.yml@main
+ uses: nswdpc/ci-files/.github/workflows/phpstan.silverstripe.yml@main
needs: Bundle
From 7536d29b466931048d58d78a4aca47a40431ef1c Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:28:50 +1000
Subject: [PATCH 29/41] (ci) Update naming
---
.github/workflows/ci.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4d57913..e58d6ee 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -4,8 +4,8 @@ on:
pull_request: null
jobs:
- Bundle:
- name: 'Automated fixes'
+ Silverstripe:
+ name: 'Silverstripe (bundle)'
uses: nswdpc/ci-files/.github/workflows/silverstripe.yml@main
PHPStan:
name: 'PHPStan (analyse)'
From fa80a8ebd968ad140ff75281adde438f3b657dc4 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:30:20 +1000
Subject: [PATCH 30/41] (ci) fix needs name
---
.github/workflows/ci.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e58d6ee..56b2b33 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,4 +10,4 @@ jobs:
PHPStan:
name: 'PHPStan (analyse)'
uses: nswdpc/ci-files/.github/workflows/phpstan.silverstripe.yml@main
- needs: Bundle
+ needs: Silverstripe
From 4e8fec51d091c6977ff4b94257cd4b5b1dca483a Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:39:07 +1000
Subject: [PATCH 31/41] (ci) use main branch for now
---
composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index 8bf15d1..8e89c4d 100644
--- a/composer.json
+++ b/composer.json
@@ -54,7 +54,7 @@
"rector/rector": "^1",
"syntro/silverstripe-phpstan": "^5",
"vlucas/phpdotenv": "^5",
- "nswdpc/ci-files": "*"
+ "nswdpc/ci-files": "dev-main"
},
"autoload": {
"psr-4": {
From c5060236604da204802eb3b3968128b231f98c84 Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Thu, 8 Aug 2024 04:44:43 +0000
Subject: [PATCH 32/41] [rector] Automated updates generated by rector
configuration
---
tests/TestSubscribeForm.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tests/TestSubscribeForm.php b/tests/TestSubscribeForm.php
index 0222114..7b2271b 100644
--- a/tests/TestSubscribeForm.php
+++ b/tests/TestSubscribeForm.php
@@ -13,7 +13,7 @@ class TestSubscribeForm extends SubscribeForm implements TestOnly
/**
* No need to spam protection on tests
*/
- public function enableSpamProtection(): null
+ public function enableSpamProtection(): mixed
{
return null;
}
From dc4bf486ebcee3a6e7cdb0b2c2cda37a429a3d8f Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:54:52 +1000
Subject: [PATCH 33/41] (ci) remove requirements installed by nswdpc/ci-files
---
composer.json | 3 ---
1 file changed, 3 deletions(-)
diff --git a/composer.json b/composer.json
index 8e89c4d..4251bfc 100644
--- a/composer.json
+++ b/composer.json
@@ -48,10 +48,7 @@
},
"require-dev": {
"cambis/silverstripe-rector": "^0.5.1",
- "friendsofphp/php-cs-fixer": "^3",
- "phpstan/phpstan": "^1",
"phpunit/phpunit": "^9.5",
- "rector/rector": "^1",
"syntro/silverstripe-phpstan": "^5",
"vlucas/phpdotenv": "^5",
"nswdpc/ci-files": "dev-main"
From e4ac6b84bf0e4b239a0f6a76e34aebd7a00583b1 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 16:15:13 +1000
Subject: [PATCH 34/41] Fix: ensure minutes value
---
src/Jobs/MailchimpCleanupJob.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 7d2e37b..5d27aff 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -24,7 +24,7 @@ class MailchimpCleanupJob extends AbstractQueuedJob implements QueuedJob
public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
{
$this->report_only = $report_only;
- $this->minutes_ago = $minutes_ago;
+ $this->minutes_ago = $minutes_ago > 0 ? $minutes_ago : 30;
$this->limit = $limit;
}
From c82cd296f9f03d396ded28e9dca86a61e2426038 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 16:19:40 +1000
Subject: [PATCH 35/41] fix: cast values as ints due mixed constructor types
---
src/Jobs/MailchimpCleanupJob.php | 5 ++++-
src/Jobs/MailchimpSubscribeJob.php | 4 +++-
2 files changed, 7 insertions(+), 2 deletions(-)
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 5d27aff..2ceb7d6 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -23,9 +23,12 @@ class MailchimpCleanupJob extends AbstractQueuedJob implements QueuedJob
public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
{
+ $minutes_ago = (int)$minutes_ago;
+ $limit = (int)$limit;
+ $report_only = (int)$report_only;
$this->report_only = $report_only;
$this->minutes_ago = $minutes_ago > 0 ? $minutes_ago : 30;
- $this->limit = $limit;
+ $this->limit = $limit > 0 ? $limit : 0;
}
#[\Override]
diff --git a/src/Jobs/MailchimpSubscribeJob.php b/src/Jobs/MailchimpSubscribeJob.php
index 314eb05..f4ae4a1 100644
--- a/src/Jobs/MailchimpSubscribeJob.php
+++ b/src/Jobs/MailchimpSubscribeJob.php
@@ -20,8 +20,10 @@ class MailchimpSubscribeJob extends AbstractQueuedJob implements QueuedJob
public function __construct($limit = 100, $report_only = 0)
{
+ $limit = (int)$limit;
+ $report_only = (int)$report_only;
$this->report_only = $report_only;
- $this->limit = (int)$limit;
+ $this->limit = $limit > 0 ? $limit : 0;
}
#[\Override]
From cc23cb61096d64ce41479bdfeabde2958b63a2ef Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 16:23:00 +1000
Subject: [PATCH 36/41] (fix) update title handling in queued jobs
---
src/Jobs/MailchimpCleanupJob.php | 17 ++++++++---------
src/Jobs/MailchimpSubscribeJob.php | 11 ++++++-----
2 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 2ceb7d6..1886740 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -31,17 +31,16 @@ public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
$this->limit = $limit > 0 ? $limit : 0;
}
- #[\Override]
public function getTitle()
{
- return sprintf(
- _t(
- self::class . '.TITLE',
- "Mailchimp cleanup job - minutes=%s limit=%s report_only=%s"
- ),
- $this->minutes_ago,
- $this->limit,
- $this->report_only
+ return _t(
+ self::class . '.TITLE',
+ "Mailchimp cleanup job - minutes={minutes} limit={limit} report_only={report_only}",
+ [
+ 'minutes' => $this->minutes_ago,
+ 'limit' => $this->limit,
+ 'report_only' => $this->report_only
+ ]
);
}
diff --git a/src/Jobs/MailchimpSubscribeJob.php b/src/Jobs/MailchimpSubscribeJob.php
index f4ae4a1..7061482 100644
--- a/src/Jobs/MailchimpSubscribeJob.php
+++ b/src/Jobs/MailchimpSubscribeJob.php
@@ -26,15 +26,16 @@ public function __construct($limit = 100, $report_only = 0)
$this->limit = $limit > 0 ? $limit : 0;
}
- #[\Override]
public function getTitle()
{
- $title = _t(
+ return _t(
self::class . '.TITLE',
- "Batch subscribe emails to Mailchimp"
+ "Batch subscribe emails to Mailchimp (limit: {limit}, report only: {report_only})",
+ [
+ 'limit' => $this->limit,
+ 'report_only' => $this->report_only
+ ]
);
- $title .= " (limit:{$this->limit})";
- return $title . ($this->report_only ? " - report only" : "");
}
#[\Override]
From 11faa42401f26b8ab5b839c5852c5ba7b674cc44 Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Thu, 8 Aug 2024 06:26:09 +0000
Subject: [PATCH 37/41] [rector] Automated updates generated by rector
configuration
---
src/Jobs/MailchimpCleanupJob.php | 3 ++-
src/Jobs/MailchimpSubscribeJob.php | 3 ++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/Jobs/MailchimpCleanupJob.php b/src/Jobs/MailchimpCleanupJob.php
index 1886740..610a606 100644
--- a/src/Jobs/MailchimpCleanupJob.php
+++ b/src/Jobs/MailchimpCleanupJob.php
@@ -27,8 +27,9 @@ public function __construct($minutes_ago = 30, $limit = 0, $report_only = 0)
$limit = (int)$limit;
$report_only = (int)$report_only;
$this->report_only = $report_only;
+
$this->minutes_ago = $minutes_ago > 0 ? $minutes_ago : 30;
- $this->limit = $limit > 0 ? $limit : 0;
+ $this->limit = max($limit, 0);
}
public function getTitle()
diff --git a/src/Jobs/MailchimpSubscribeJob.php b/src/Jobs/MailchimpSubscribeJob.php
index 7061482..ceed02a 100644
--- a/src/Jobs/MailchimpSubscribeJob.php
+++ b/src/Jobs/MailchimpSubscribeJob.php
@@ -23,7 +23,8 @@ public function __construct($limit = 100, $report_only = 0)
$limit = (int)$limit;
$report_only = (int)$report_only;
$this->report_only = $report_only;
- $this->limit = $limit > 0 ? $limit : 0;
+
+ $this->limit = max($limit, 0);
}
public function getTitle()
From 4c5b37d8cc9357440e2c4d472abf2da4f88e683d Mon Sep 17 00:00:00 2001
From: James Ellis <69664712+JamesDPC@users.noreply.github.com>
Date: Thu, 8 Aug 2024 17:08:58 +1000
Subject: [PATCH 38/41] Update Silverstripe reusable workflow
---
.github/workflows/ci.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 56b2b33..43b8947 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,7 +6,7 @@ on:
jobs:
Silverstripe:
name: 'Silverstripe (bundle)'
- uses: nswdpc/ci-files/.github/workflows/silverstripe.yml@main
+ uses: nswdpc/ci-files/.github/workflows/silverstripe_5_81.yml@main
PHPStan:
name: 'PHPStan (analyse)'
uses: nswdpc/ci-files/.github/workflows/phpstan.silverstripe.yml@main
From a0e75d8b37f4e2fa909aba93bac21d11cb986d26 Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Fri, 9 Aug 2024 01:33:21 +0000
Subject: [PATCH 39/41] [rector] Automated updates generated by rector
configuration
---
src/Controllers/ChimpleController.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 324675a..820fc1e 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -88,7 +88,7 @@ public function HideGenericChimpleForm()
* This returns false to avoid the form being included in generic $Form templates/layouts
* Use $ChimpleSubscribeForm('some-code') in templates instead
*/
- public function Form()
+ public function Form(): bool
{
return false;
}
@@ -261,7 +261,7 @@ protected function getCallbackForXhrValidation(): callable
*/
protected function getCallbackForValidation(SubscribeForm $form): callable
{
- return function (ValidationResult $result) use ($form) {
+ return function (ValidationResult $result) use ($form): \SilverStripe\Control\HTTPResponse {
// Prior to redirection, persist this result in session to re-display on redirect
$form->setSessionValidationResult($result);
$form->setSessionData($form->getData());
From 2d2088792d268f013c06126a3d4c3eedbd5a97ce Mon Sep 17 00:00:00 2001
From: JamesDPC
Date: Fri, 9 Aug 2024 02:03:06 +0000
Subject: [PATCH 40/41] [rector] Automated updates generated by rector
configuration
---
src/Controllers/ChimpleController.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/Controllers/ChimpleController.php b/src/Controllers/ChimpleController.php
index 324675a..820fc1e 100644
--- a/src/Controllers/ChimpleController.php
+++ b/src/Controllers/ChimpleController.php
@@ -88,7 +88,7 @@ public function HideGenericChimpleForm()
* This returns false to avoid the form being included in generic $Form templates/layouts
* Use $ChimpleSubscribeForm('some-code') in templates instead
*/
- public function Form()
+ public function Form(): bool
{
return false;
}
@@ -261,7 +261,7 @@ protected function getCallbackForXhrValidation(): callable
*/
protected function getCallbackForValidation(SubscribeForm $form): callable
{
- return function (ValidationResult $result) use ($form) {
+ return function (ValidationResult $result) use ($form): \SilverStripe\Control\HTTPResponse {
// Prior to redirection, persist this result in session to re-display on redirect
$form->setSessionValidationResult($result);
$form->setSessionData($form->getData());
From f0c083c0093b778d22845697d767abbe54e6b753 Mon Sep 17 00:00:00 2001
From: "James (DPC)" <69664712+JamesDPC@users.noreply.github.com>
Date: Fri, 9 Aug 2024 12:24:14 +1000
Subject: [PATCH 41/41] (ci) switch to tag ref
---
.github/workflows/ci.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 56b2b33..6f6221b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,8 +6,8 @@ on:
jobs:
Silverstripe:
name: 'Silverstripe (bundle)'
- uses: nswdpc/ci-files/.github/workflows/silverstripe.yml@main
+ uses: nswdpc/ci-files/.github/workflows/silverstripe.yml@1.1.0
PHPStan:
name: 'PHPStan (analyse)'
- uses: nswdpc/ci-files/.github/workflows/phpstan.silverstripe.yml@main
+ uses: nswdpc/ci-files/.github/workflows/phpstan.silverstripe.yml@1.1.0
needs: Silverstripe