Метод Str::repeat у Laravel пропонує просте рішення для створення повторюваних строкових шаблонів шляхом копіювання рядка певну кількість разів
Як повторити рядок визначену кількість разів:
use Illuminate\Support\Str;
$character = 'x';
$repeated = Str::repeat($character, 4);
// Результат: 'xxxx'
Ось приклад використання у форматувальнику звітів:
class ReportFormatter
{
public function createSeparatorLine(int $length = 50)
{
return sprintf(
'%s%s%s',
'+',
Str::repeat('-', $length - 2),
'+'
);
}
public function formatProgressBar(int $completed, int $total = 10)
{
$progress = Str::repeat('█', $completed);
$remaining = Str::repeat('░', $total - $completed);
return sprintf(
'[%s%s] %d%%',
$progress,
$remaining,
($completed / $total) * 100
);
}
public function createIndentation(int $level)
{
return sprintf(
'%s%s',
Str::repeat(' ', $level),
'- '
);
}
}
$formatter = new ReportFormatter();
echo $formatter->createSeparatorLine(30);
// Вихід: +----------------------------+
echo $formatter->formatProgressBar(7);
// Вихід: [███████░░░] 70%
echo $formatter->createIndentation(3);
// Вихід: -
Метод repeat забезпечує зручний спосіб роботи із задачами повторення рядків у ваших додатках Laravel