4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Helper;
14 use Symfony\Component\Console\Formatter\OutputFormatterInterface;
17 * Helper is the base class for all helper classes.
19 * @author Fabien Potencier <fabien@symfony.com>
21 abstract class Helper implements HelperInterface
23 protected $helperSet = null;
26 * Sets the helper set associated with this helper.
28 * @param HelperSet $helperSet A HelperSet instance
30 public function setHelperSet(HelperSet $helperSet = null)
32 $this->helperSet = $helperSet;
36 * Gets the helper set associated with this helper.
38 * @return HelperSet|null
40 public function getHelperSet()
42 return $this->helperSet;
46 * Returns the length of a string, using mb_strwidth if it is available.
48 * @param string $string The string to check its length
50 * @return int The length of the string
52 public static function strlen($string)
54 if (false === $encoding = mb_detect_encoding($string, null, true)) {
55 return strlen($string);
58 return mb_strwidth($string, $encoding);
61 public static function formatTime($secs)
63 static $timeFormats = array(
68 array(120, 'mins', 60),
70 array(7200, 'hrs', 3600),
71 array(86400, '1 day'),
72 array(172800, 'days', 86400),
75 foreach ($timeFormats as $index => $format) {
76 if ($secs >= $format[0]) {
77 if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
78 || $index == count($timeFormats) - 1
80 if (2 == count($format)) {
84 return floor($secs / $format[2]).' '.$format[1];
90 public static function formatMemory($memory)
92 if ($memory >= 1024 * 1024 * 1024) {
93 return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
96 if ($memory >= 1024 * 1024) {
97 return sprintf('%.1f MiB', $memory / 1024 / 1024);
100 if ($memory >= 1024) {
101 return sprintf('%d KiB', $memory / 1024);
104 return sprintf('%d B', $memory);
107 public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
109 return self::strlen(self::removeDecoration($formatter, $string));
112 public static function removeDecoration(OutputFormatterInterface $formatter, $string)
114 $isDecorated = $formatter->isDecorated();
115 $formatter->setDecorated(false);
116 // remove <...> formatting
117 $string = $formatter->format($string);
118 // remove already formatted characters
119 $string = preg_replace("/\033\[[^m]*m/", '', $string);
120 $formatter->setDecorated($isDecorated);