@ 2023-11-24T21:33:36Z <?php
abstract class StringObject {
protected string $string;
public function __toString(): string {
return $this->string;
}
}
class StringObjectException extends Exception {
public readonly string $string;
public function __construct(string $string, string $message = "", int $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->string = $string;
}
}
class CountableString extends StringObject {
private int $lettersCount;
public function __construct(string $string) {
$this->string = $string;
$this->lettersCount = mb_strlen($string);
}
public function countLetters(): int {
return $this->lettersCount;
}
}
class EmptyStringException extends StringObjectException {}
class NotEmptyString extends StringObject {
/**
* @throws EmptyStringException
*/
public function __construct(string $string) {
if ('' === $string) {
throw new EmptyStringException(string: $string, message: 'Expected not empty string.');
}
$this->string = $string;
}
}
class TooLongStringException extends StringObjectException {}
class LimitedLengthString extends StringObject {
/**
* @throws TooLongStringException
*/
public function __construct(CountableString $string, int $maxLength) {
if ($maxLength < $string->countLetters()) {
throw new TooLongStringException(string: $string, message: 'Too long string');
}
$this->string = $string;
}
}
class TenLettersStringValidator {
private const MAX_LETTERS_COUNT = 10;
private const ERROR_MESSAGE = 'Expected string not longer then: "%d letters" got: "%s"';
public function __invoke(string $string): ?string {
$error = null;
try {
new LimitedLengthString(new CountableString($string), self::MAX_LETTERS_COUNT);
} catch (TooLongStringException $exception) {
$error = sprintf(self::ERROR_MESSAGE,
self::MAX_LETTERS_COUNT,
$exception->string
);
}
return $error;
}
}
$validators = [new TenLettersStringValidator];
$errors = [];
$string = 'Тестовая строка';
foreach ($validators as $validator) {
$result = $validator($string);
$result ? $errors[] = $result : null;
}
var_dump($errors);
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 8.4.1 - 8.4.12 Deprecated: StringObjectException::__construct(): Implicitly marking parameter $previous as nullable is deprecated, the explicit nullable type must be used instead in /in/jGPb4 on line 14
array(1) {
[0]=>
string(82) "Expected string not longer then: "10 letters" got: "Тестовая строка""
}
Output for 8.1.0 - 8.1.33 , 8.2.0 - 8.2.29 , 8.3.0 - 8.3.25 array(1) {
[0]=>
string(82) "Expected string not longer then: "10 letters" got: "Тестовая строка""
}
Output for 8.0.1 - 8.0.30 Parse error: syntax error, unexpected identifier "string", expecting variable in /in/jGPb4 on line 12
Process exited with code 255 . preferences:dark mode live preview ace vim emacs key bindings
67.32 ms | 408 KiB | 5 Q