<?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);
- Output for git.master, git.master_jit, rfc.property-hooks
- array(1) {
[0]=>
string(82) "Expected string not longer then: "10 letters" got: "Тестовая строка""
}
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches
Archived branches
Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:
25.78 ms | 405 KiB | 5 Q