Skip to content

Commit 4a9e895

Browse files
committed
Fix: phpcs
1 parent 04e84a1 commit 4a9e895

19 files changed

Lines changed: 175 additions & 109 deletions

config/PhpCodeSniffer/ruleset.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@
5454
<!-- Functions -->
5555
<rule ref="Squiz.Functions.FunctionDuplicateArgument"/>
5656
<rule ref="Squiz.Functions.GlobalFunction"/>
57+
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
58+
<properties>
59+
<property name="ignoreNewlines" value="true"/>
60+
</properties>
61+
</rule>
5762

5863
<!-- Metrics -->
5964
<rule ref="Generic.Metrics.CyclomaticComplexity"/>

src/Domain/Common/ExternalImageService.php

Lines changed: 43 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@
66

77
use PhpList\Core\Domain\Configuration\Model\ConfigOption;
88
use PhpList\Core\Domain\Configuration\Service\Provider\ConfigProvider;
9+
use Psr\Log\LoggerInterface;
10+
use Throwable;
911

1012
class ExternalImageService
1113
{
1214
private string $externalCacheDir;
1315

1416
public function __construct(
1517
private readonly ConfigProvider $configProvider,
18+
private readonly LoggerInterface $logger,
1619
private readonly string $tempDir,
1720
private readonly int $externalImageMaxAge,
1821
private readonly int $externalImageMaxSize,
@@ -74,26 +77,31 @@ public function cache($filename, $messageId): bool
7477

7578
private function removeOldFilesInCache(): void
7679
{
80+
// phpcs:ignore Generic.PHP.NoSilencedErrors
7781
$extCacheDirHandle = @opendir($this->externalCacheDir);
7882
if (!$this->externalImageMaxAge || !$extCacheDirHandle) {
79-
return;
83+
return;
8084
}
8185

82-
while (($cacheFile = @readdir($extCacheDirHandle)) !== false) {
86+
while (true) {
87+
// phpcs:ignore Generic.PHP.NoSilencedErrors
88+
$cacheFile = @readdir($extCacheDirHandle);
89+
90+
if ($cacheFile === false) {
91+
break;
92+
}
8393
// todo: make sure that this is what we need
8494
if (!str_starts_with($cacheFile, '.')) {
85-
$cacheFileMTime = @filemtime($this->externalCacheDir.'/'.$cacheFile);
86-
87-
if (
88-
is_numeric($cacheFileMTime)
89-
&& ($cacheFileMTime > 0)
90-
&& ((time() - $cacheFileMTime) > $this->externalImageMaxAge)
91-
) {
92-
@unlink($this->externalCacheDir.'/'.$cacheFile);
95+
// phpcs:ignore Generic.PHP.NoSilencedErrors
96+
$cfmt = @filemtime($this->externalCacheDir . '/' . $cacheFile);
97+
98+
if (is_numeric($cfmt) && ($cfmt > 0) && ((time() - $cfmt) > $this->externalImageMaxAge)) {
99+
// phpcs:ignore Generic.PHP.NoSilencedErrors
100+
@unlink($this->externalCacheDir . '/' . $cacheFile);
93101
}
94102
}
95103
}
96-
104+
// phpcs:ignore Generic.PHP.NoSilencedErrors
97105
@closedir($extCacheDirHandle);
98106
}
99107

@@ -158,8 +166,7 @@ private function downloadUsingFileGetContent(string $filename): string
158166

159167
private function isCacheableUrl($filename): bool
160168
{
161-
if (
162-
!(str_starts_with($filename, 'http'))
169+
if (!(str_starts_with($filename, 'http'))
163170
|| str_contains($filename, '://' . $this->configProvider->getValue(ConfigOption::Website) . '/')
164171
) {
165172
return false;
@@ -172,6 +179,7 @@ private function ensureCacheDirectory(): bool
172179
{
173180

174181
if (!file_exists($this->externalCacheDir)) {
182+
// phpcs:ignore Generic.PHP.NoSilencedErrors
175183
@mkdir($this->externalCacheDir);
176184
}
177185

@@ -184,7 +192,7 @@ private function ensureCacheDirectory(): bool
184192

185193
private function isValidCacheFile(string $cacheFileName): bool
186194
{
187-
195+
// phpcs:ignore Generic.PHP.NoSilencedErrors
188196
if (file_exists($cacheFileName) && (@filesize($cacheFileName) > 64)) {
189197
return true;
190198
}
@@ -194,14 +202,28 @@ private function isValidCacheFile(string $cacheFileName): bool
194202

195203
private function writeCacheFile(string $cacheFileName, $content): void
196204
{
197-
$cacheFileHandle = @fopen($cacheFileName, 'wb');
198-
if ($cacheFileHandle !== false) {
199-
if (flock($cacheFileHandle, LOCK_EX)) {
200-
fwrite($cacheFileHandle, $content);
201-
fflush($cacheFileHandle);
202-
flock($cacheFileHandle, LOCK_UN);
205+
try {
206+
$handle = fopen($cacheFileName, 'wb');
207+
208+
if ($handle === false) {
209+
$this->logger->error('Cannot open cache file', [
210+
'file' => $cacheFileName,
211+
]);
212+
return;
213+
}
214+
215+
if (flock($handle, LOCK_EX)) {
216+
fwrite($handle, $content);
217+
fflush($handle);
218+
flock($handle, LOCK_UN);
203219
}
204-
fclose($cacheFileHandle);
220+
221+
fclose($handle);
222+
} catch (Throwable $e) {
223+
$this->logger->error('Cache file write failed', [
224+
'file' => $cacheFileName,
225+
'error' => $e->getMessage(),
226+
]);
205227
}
206228
}
207229
}

src/Domain/Common/Html2Text.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,21 @@ public function __invoke(string $html): string
1919
{
2020
$text = preg_replace("/\r/", '', $html);
2121

22-
$text = preg_replace("/<script[^>]*>(.*?)<\/script\s*>/is", '', $text);
23-
$text = preg_replace("/<style[^>]*>(.*?)<\/style\s*>/is", '', $text);
22+
$text = preg_replace('/<script[^>]*>(.*?)<\/script\s*>/is', '', $text);
23+
$text = preg_replace('/<style[^>]*>(.*?)<\/style\s*>/is', '', $text);
2424

2525
$text = preg_replace(
2626
"/<a[^>]*href=([\"\'])(.*)\\1[^>]*>(.*)<\/a>/Umis",
2727
"[URLTEXT]\\3[ENDURLTEXT][LINK]\\2[ENDLINK]\n",
2828
$text
2929
);
30-
$text = preg_replace("/<b>(.*?)<\/b\s*>/is", '*\\1*', $text);
31-
$text = preg_replace("/<h[\d]>(.*?)<\/h[\d]\s*>/is", "**\\1**\n", $text);
32-
$text = preg_replace("/<i>(.*?)<\/i\s*>/is", '/\\1/', $text);
33-
$text = preg_replace("/<\/tr\s*?>/i", "<\/tr>\n\n", $text);
34-
$text = preg_replace("/<\/p\s*?>/i", "<\/p>\n\n", $text);
30+
$text = preg_replace('/<b>(.*?)<\/b\s*>/is', '*\\1*', $text);
31+
$text = preg_replace('/<h[\d]>(.*?)<\/h[\d]\s*>/is', "**\\1**\n", $text);
32+
$text = preg_replace('/<i>(.*?)<\/i\s*>/is', '/\\1/', $text);
33+
$text = preg_replace('/<\/tr\s*?>/i', "<\/tr>\n\n", $text);
34+
$text = preg_replace('/<\/p\s*?>/i', "<\/p>\n\n", $text);
3535
$text = preg_replace('/<br[^>]*?>/i', "<br>\n", $text);
36-
$text = preg_replace("/<br[^>]*?\/>/i", "<br\/>\n", $text);
36+
$text = preg_replace('/<br[^>]*?\/>/i', "<br\/>\n", $text);
3737
$text = preg_replace('/<table/i', "\n\n<table", $text);
3838
$text = strip_tags($text);
3939

src/Domain/Common/HtmlUrlRewriter.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class HtmlUrlRewriter
1212
{
1313
public function addAbsoluteResources(string $html, string $baseUrl): string
1414
{
15-
$baseUrl = rtrim($baseUrl, "/");
15+
$baseUrl = rtrim($baseUrl, '/');
1616

1717
// 1) Rewrite HTML attributes via DOM (handles quotes, whitespace, etc.)
1818
$dom = new DOMDocument();
@@ -113,7 +113,9 @@ private function normalizePath(string $path): string
113113
$segments = explode('/', $parts['path'] ?? $path);
114114
$out = [];
115115
foreach ($segments as $seg) {
116-
if ($seg === '' || $seg === '.') continue;
116+
if ($seg === '' || $seg === '.') {
117+
continue;
118+
}
117119
if ($seg === '..') {
118120
array_pop($out);
119121
continue;
@@ -172,10 +174,9 @@ function ($matches) use ($baseUrl) {
172174
$quotes = trim($matches[1]);
173175
$url = $matches[2];
174176
$abs = $this->absolutizeUrl($url, $baseUrl);
177+
$import = ($quotes ?: '') . $abs . ($quotes ?: '');
175178
// Preserve original form loosely
176-
return str_starts_with($matches[0], '@import url')
177-
? '@import url(' . ($quotes ?: '') . $abs . ($quotes ?: '') . ')'
178-
: '@import ' . ($quotes ?: '') . $abs . ($quotes ?: '');
179+
return '@import ' . (str_starts_with($matches[0], '@import url') ? 'url(' . $import . ')' : $import);
179180
},
180181
$css
181182
);

src/Domain/Common/TextParser.php

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ public function __invoke(string $text): string
1010
{
1111
$text = ltrim($text);
1212
$text = preg_replace(
13-
"/([\._a-z0-9-]+@[\.a-z0-9-]+)/i",
13+
'/([\._a-z0-9-]+@[\.a-z0-9-]+)/i',
1414
'<a href="mailto:\\1" class="email">\\1</a>',
1515
$text,
1616
);
17-
$linkPattern = "/(.*)<a.*href\s*=\s*\"(.*?)\"\s*(.*?)>(.*?)<\s*\/a\s*>(.*)/is";
17+
$linkPattern = '/(.*)<a.*href\s*=\s*\"(.*?)\"\s*(.*?)>(.*?)<\s*\/a\s*>(.*)/is';
1818
$link = [];
1919
$index = 0;
2020
while (preg_match($linkPattern, $text, $matches)) {
@@ -25,47 +25,47 @@ public function __invoke(string $text): string
2525
//<a href="javascript:window.open('http://hacker.com?cookie='+document.cookie)">
2626
$url = preg_replace('/:/', '', $url);
2727
}
28-
$link[$index] = '<a href="'.$url.'" '.$rest.'>'.$matches[4].'</a>';
29-
$text = $matches[1]."%%$index%%".$matches[5];
28+
$link[$index] = '<a href=" ' .$url . '" ' . $rest . '>' . $matches[4] . '</a>';
29+
$text = $matches[1] . '%%' . $index . '%%' . $matches[5];
3030
++$index;
3131
}
3232

3333
//make www. -> http://www.
34-
$text = preg_replace("/(www\.[a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i", 'http://\\1', $text);
34+
$text = preg_replace('/(www\.[a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i', 'http://\\1', $text);
3535
//take out duplicate schema
36-
$text = preg_replace("/(https?:\/\/)http?:\/\//i", '\\1', $text);
37-
$text = preg_replace("/(ftp:\/\/)http?:\/\//i", '\\1', $text);
36+
$text = preg_replace('/(https?:\/\/)http?:\/\//i', '\\1', $text);
37+
$text = preg_replace('/(ftp:\/\/)http?:\/\//i', '\\1', $text);
3838
//eg-- http://kernel.org -> <a href"http://kernel.org" target="_blank">http://kernel.org</a>
3939
$text = preg_replace(
40-
"/(https?:\/\/)(?!www)([a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i",
40+
'/(https?:\/\/)(?!www)([a-zA-Z0-9\.\/#~:?+=&%@!_\\-]+)/i',
4141
'<a href="\\1\\2" class="url" target="_blank">\\2</a>',
4242
$text
4343
);
4444
//eg -- http://www.google.com -> <a href"http://www.google.com" target="_blank">www.google.com</a>
4545
$text = preg_replace(
46-
"/(https?:\/\/)(www\.)([a-zA-Z0-9\.\/#~:?+=&%@!\\-_]+)/i",
46+
'/(https?:\/\/)(www\.)([a-zA-Z0-9\.\/#~:?+=&%@!\\-_]+)/i',
4747
'<a href="\\1\\2\\3" class="url" target="_blank">\\2\\3</a>',
4848
$text
4949
);
5050

5151
// take off a possible last full stop and move it outside
5252
$text = preg_replace(
53-
"/<a href=\"(.*?)\.\" class=\"url\" target=\"_blank\">(.*)\.<\/a>/i",
53+
'/<a href=\"(.*?)\.\" class=\"url\" target=\"_blank\">(.*)\.<\/a>/i',
5454
'<a href="\\1" class="url" target="_blank">\\2</a>.',
5555
$text
5656
);
5757

5858
for ($j = 0; $j < $index; ++$j) {
5959
$replacement = $link[$j];
60-
$text = preg_replace("/\%\%$j\%\%/", $replacement, $text);
60+
$text = preg_replace('/\%\%' . $j . '\%\%/', $replacement, $text);
6161
}
6262

6363
// hmm, regular expression choke on some characters in the text
6464
// first replace all the brackets with placeholders.
6565
// we cannot use htmlspecialchars or addslashes, because some are needed
6666

67-
$text = str_replace("\(", '<!--LB-->', $text);
68-
$text = str_replace("\)", '<!--RB-->', $text);
67+
$text = str_replace('\(', '<!--LB-->', $text);
68+
$text = str_replace('\)', '<!--RB-->', $text);
6969
$text = preg_replace('/\$/', '<!--DOLL-->', $text);
7070

7171
// @@@ to be xhtml compabible we'd have to close the <p> as well

src/Domain/Identity/Repository/AdminAttributeDefinitionRepository.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public function getForAdmin(Administrator $admin): array
3838
public function getAllWithEmptyValues(): array
3939
{
4040
return $this->createQueryBuilder('ad')
41-
->select("ad.name AS name", "'' AS value")
41+
->select('ad.name AS name', "'' AS value")
4242
->getQuery()
4343
->getResult();
4444
}

src/Domain/Messaging/EventSubscriber/InjectedByHeaderSubscriber.php

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,16 @@ public function onMessage(MessageEvent $event): void
3030
// todo: add custom header only to messages sent individually not from campaigns
3131
// when the email is generated from a webpage (quite possible :-) add a "received line" to identify the origin
3232
$msg = $event->getMessage();
33-
if (!$msg instanceof Email)
34-
{
33+
if (!$msg instanceof Email) {
3534
return;
3635
}
3736

3837
// Only when triggered by HTTP request context (not CLI workers)
39-
if (PHP_SAPI === 'cli')
40-
{
38+
if (PHP_SAPI === 'cli') {
4139
return;
4240
}
4341

44-
$ip = $request->getClientIp() ?? 'unknown';
42+
$ip = $request->getClientIp() ?? 'unknown';
4543
$host = gethostname() ?: 'unknown-host';
4644

4745
$timestamp = $request->server->get('REQUEST_TIME') ?? time();

src/Domain/Messaging/MessageHandler/CampaignProcessorMessageHandler.php

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,8 @@ public function __invoke(CampaignProcessorMessage|SyncCampaignProcessorMessage $
138138
// }
139139
// $req = Sql_Query($query);
140140
// while ($row = Sql_Fetch_Row($req)) {
141-
// $um = Sql_Query(sprintf('replace into %s (entered,userid,messageid,status) values(now(),%d,%d,"excluded")',
141+
// $um = Sql_Query(sprintf('replace into %s (entered,userid,messageid,status)
142+
// values(now(),%d,%d,"excluded")',
142143
// $tables['usermessage'], $row[0], $messageid));
143144
// }
144145
// }
@@ -200,8 +201,15 @@ private function handleEmailSending(
200201
UserMessage $userMessage,
201202
MessagePrecacheDto $precachedContent,
202203
): void {
203-
$processed = $this->messagePreparator->processMessageLinks($campaign->getId(), $precachedContent, $subscriber);
204-
$processed->textContent = $this->userPersonalizer->personalize($processed->textContent, $subscriber->getEmail());
204+
$processed = $this->messagePreparator->processMessageLinks(
205+
$campaign->getId(),
206+
$precachedContent,
207+
$subscriber
208+
);
209+
$processed->textContent = $this->userPersonalizer->personalize(
210+
$processed->textContent,
211+
$subscriber->getEmail(),
212+
);
205213
$processed->footer = $this->userPersonalizer->personalize($processed->footer, $subscriber->getEmail());
206214

207215
try {
@@ -312,7 +320,9 @@ private function handleAdminNotifications(Message $campaign, array $loadedMessag
312320
$this->entityManager->persist($messageData);
313321
$this->entityManager->flush();
314322
} catch (UniqueConstraintViolationException $e) {
315-
// equivalent to IGNORE — do nothing
323+
$this->logger->debug('Duplicate message ignored', [
324+
'exception' => $e,
325+
]);
316326
}
317327
}
318328
}

src/Domain/Messaging/Model/Dto/MessagePrecacheDto.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ class MessagePrecacheDto
2323
public ?string $template = null;
2424
public ?string $templateText = null;
2525
public ?int $templateId = null;
26-
public string $htmlCharset= 'UTF-8';
27-
public string $textCharset= 'UTF-8';
26+
// public string $htmlCharset= 'UTF-8';
27+
// public string $textCharset= 'UTF-8';
2828
public bool $userSpecificUrl;
2929
public string $googleTrack;
3030
public array $adminAttributes = [];

src/Domain/Messaging/Service/Builder/EmailBuilder.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ private function validateRecipientAndSubject(?string $to, ?string $subject): boo
9393
return false;
9494
}
9595
if (!$subject) {
96-
$this->eventLogManager->log('', "Error: empty Subject: in message to send to $to");
96+
$this->eventLogManager->log('', sprintf('Error: empty Subject: in message to send to %s', $to));
9797

9898
return false;
9999
}
@@ -131,7 +131,7 @@ private function resolveDestinationEmailAndMessage(?string $to, ?string $message
131131
$destinationEmail = '';
132132

133133
if ($this->devVersion) {
134-
$message = "To: $to\n".$message;
134+
$message = 'To: ' . $to . PHP_EOL . $message;
135135
if ($this->devEmail) {
136136
$destinationEmail = $this->devEmail;
137137
}
@@ -197,7 +197,8 @@ private function applyContentAndFormatting(Email $email, $htmlMessage, $textMess
197197
$email->html($htmlMessage);
198198
$email->text($textMessage);
199199
($this->templateImageEmbedder)(html: $htmlMessage, messageId: $messageId);
200-
//# In the above phpMailer strips all tags, which removes the links which are wrapped in < and > by HTML2text
200+
//# In the above phpMailer strips all tags, which removes the links
201+
// which are wrapped in < and > by HTML2text
201202
//# so add it again
202203
$email->text($textMessage);
203204
}

0 commit comments

Comments
 (0)