1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108:
<?php
/*
* This file is part of the webmozart/console package.
*
* (c) Bernhard Schussek <bschussek@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webmozart\Console\UI\Alignment;
use Webmozart\Console\Api\Formatter\Formatter;
use Webmozart\Console\UI\Component\LabeledParagraph;
/**
* Aligns labeled paragraphs.
*
* The alignment takes {@link LabeledParagraph} instances and aligns the texts
* next to the labels so that all texts start at the same offset. Pass the
* paragraphs that you want to align to {@link add()}. When you call
* {@link align()}, the text offset is calculated. You can retrieve the
* calculated offset with {@link getTextOffset()}.
*
* @since 1.0
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class LabelAlignment
{
/**
* @var LabeledParagraph[]
*/
private $paragraphs = array();
/**
* @var int[]
*/
private $indentations = array();
/**
* @var int
*/
private $textOffset = 0;
/**
* Adds a labeled paragraph to the alignment.
*
* @param LabeledParagraph $paragraph The labeled paragraph.
* @param int $indentation The indentation of the paragraph.
*/
public function add(LabeledParagraph $paragraph, $indentation = 0)
{
if ($paragraph->isAligned()) {
$this->paragraphs[] = $paragraph;
$this->indentations[] = $indentation;
}
}
/**
* Calculates the text offset based on all labels in the alignment.
*
* The passed indentation is added to the indentations of all labeled
* paragraphs.
*
* @param Formatter $formatter The formatter used to remove style tags when
* calculating the label width.
* @param int $indentation The indentation.
*/
public function align(Formatter $formatter, $indentation = 0)
{
$this->textOffset = 0;
foreach ($this->paragraphs as $i => $item) {
$label = $formatter->removeFormat($item->getLabel());
$textOffset = $this->indentations[$i] + strlen($label) + $item->getPadding();
$this->textOffset = max($this->textOffset, $textOffset);
}
$this->textOffset += $indentation;
}
/**
* Manually sets the text offset.
*
* @param int $textOffset The text offset.
*/
public function setTextOffset($textOffset)
{
$this->textOffset = $textOffset;
}
/**
* Returns the calculated text offset.
*
* Before calling {@link align()} or {@link setTextOffset()}, this method
* returns 0.
*
* @return int The text offset.
*/
public function getTextOffset()
{
return $this->textOffset;
}
}