- mb_strlen: documentation ( source)
- sprintf: documentation ( source)
<?php
abstract class StringObject {
protected string $string;
public function __tostring(): string {
return $this->string;
}
}
class StringObjectException extends Exception {}
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 Exception {};
class NotEmptyString extends StringObject {
public function __construct(string $string) {
if ('' === $string) {
throw new EmptyStringException('Expected not empty string.');
}
$this->string = $string;
}
}
class TooLongStringException extends Exception {};
class TenLettersString extends StringObject {
private const MAX_LETTERS_COUNT = 10;
public function __construct(CountableString $string) {
if (self::MAX_LETTERS_COUNT < $string->countLetters()) {
throw new TooLongStringException(
sprintf('Expected string not longer then: "%d letters" got: "%s"',
self::MAX_LETTERS_COUNT,
$string
)
);
}
$this->string = $string;
}
}
$countableString = new CountableString('Тестовая строка');
$notEmptyString = new NotEmptyString($countableString);
echo $countableString->countLetters() . PHP_EOL;
echo $countableString . PHP_EOL;
$tenLetterLongString = new TenLettersString($countableString);