<?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);
preferences:
29.62 ms | 406 KiB | 5 Q