Skip to content

Commit 14a8249

Browse files
committed
Refactored the legal url comparison
1 parent adc89cd commit 14a8249

1 file changed

Lines changed: 35 additions & 27 deletions

File tree

src/Cas/ServiceValidator.php

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -53,35 +53,9 @@ public function checkServiceURL(string $service): ?Configuration
5353

5454
$configOverride = \is_int($index) ? null : $value;
5555

56-
// URL String
57-
if (str_starts_with($service, $legalUrl)) {
58-
$isValidService = true;
56+
if ($isValidService = $this->validateServiceIsLegal($legalUrl, $service)) {
5957
break;
6058
}
61-
62-
// Regex
63-
// Since "If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. "
64-
// we will throw an exception if the warning is emitted and use try-catch to handle it
65-
set_error_handler(static function ($severity, $message, $file, $line) {
66-
throw new \ErrorException($message, $severity, $severity, $file, $line);
67-
}, E_WARNING);
68-
69-
try {
70-
$result = preg_match($legalUrl, $service);
71-
if ($result !== 1) {
72-
throw new \RuntimeException('Service URL does not match legal service URL.');
73-
}
74-
$isValidService = true;
75-
break;
76-
} catch (\RuntimeException $e) {
77-
// do nothing
78-
Logger::warning($e->getMessage());
79-
} catch (\Exception $e) {
80-
// do nothing
81-
Logger::warning("Invalid CAS legal service url '$legalUrl'. Error " . preg_last_error());
82-
} finally {
83-
restore_error_handler();
84-
}
8559
}
8660

8761
if (!$isValidService) {
@@ -107,4 +81,38 @@ public function checkServiceURL(string $service): ?Configuration
10781
}
10882
return Configuration::loadFromArray($serviceConfig);
10983
}
84+
85+
/**
86+
* @param string $legalUrl The string or regex to use for comparison
87+
* @param string $service The service to compare
88+
*
89+
* @return bool Whether the service is legal
90+
* @throws \ErrorException
91+
*/
92+
protected function validateServiceIsLegal(string $legalUrl, string $service): bool
93+
{
94+
$isValid = false;
95+
if (!ctype_alnum($legalUrl[0])) {
96+
// Since "If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted. "
97+
// we will throw an exception if the warning is emitted and use try-catch to handle it
98+
set_error_handler(static function ($severity, $message, $file, $line) {
99+
throw new \ErrorException($message, $severity, $severity, $file, $line);
100+
}, E_WARNING);
101+
102+
try {
103+
if (preg_match($legalUrl, $service) === 1) {
104+
$isValid = true;
105+
}
106+
} catch (\ErrorException $e) {
107+
// do nothing
108+
Logger::warning("Invalid CAS legal service url '$legalUrl'. Error " . preg_last_error_msg());
109+
} finally {
110+
restore_error_handler();
111+
}
112+
} elseif (str_starts_with($service, $legalUrl)) {
113+
$isValid = true;
114+
}
115+
116+
return $isValid;
117+
}
110118
}

0 commit comments

Comments
 (0)