Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. OutputFormatter.php

class OutputFormatter

Formatter class for console output.

@author Konstantin Kudryashov <ever.zet@gmail.com> @author Roland Franssen <franssen.roland@gmail.com>

Hierarchy

  • class \Symfony\Component\Console\Formatter\OutputFormatter implements \Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface

Expanded class hierarchy of OutputFormatter

18 files declare their use of OutputFormatter
Application.php in vendor/symfony/console/Application.php
Auditor.php in vendor/composer/composer/src/Composer/Advisory/Auditor.php
AutoloadGenerator.php in vendor/composer/composer/src/Composer/Autoload/AutoloadGenerator.php
BaseDependencyCommand.php in vendor/composer/composer/src/Composer/Command/BaseDependencyCommand.php
Factory.php in vendor/composer/composer/src/Composer/Factory.php

... See full list

File

vendor/symfony/console/Formatter/OutputFormatter.php, line 24

Namespace

Symfony\Component\Console\Formatter
View source
class OutputFormatter implements WrappableOutputFormatterInterface {
    private array $styles = [];
    private OutputFormatterStyleStack $styleStack;
    public function __clone() {
        $this->styleStack = clone $this->styleStack;
        foreach ($this->styles as $key => $value) {
            $this->styles[$key] = clone $value;
        }
    }
    
    /**
     * Escapes "<" and ">" special chars in given text.
     */
    public static function escape(string $text) : string {
        $text = preg_replace('/([^\\\\]|^)([<>])/', '$1\\\\$2', $text);
        return self::escapeTrailingBackslash($text);
    }
    
    /**
     * Escapes trailing "\" in given text.
     *
     * @internal
     */
    public static function escapeTrailingBackslash(string $text) : string {
        if (str_ends_with($text, '\\')) {
            $len = \strlen($text);
            $text = rtrim($text, '\\');
            $text = str_replace("\x00", '', $text);
            $text .= str_repeat("\x00", $len - \strlen($text));
        }
        return $text;
    }
    
    /**
     * Initializes console output formatter.
     *
     * @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
     */
    public function __construct(bool $decorated = false, array $styles = []) {
        $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
        $this->setStyle('info', new OutputFormatterStyle('green'));
        $this->setStyle('comment', new OutputFormatterStyle('yellow'));
        $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
        foreach ($styles as $name => $style) {
            $this->setStyle($name, $style);
        }
        $this->styleStack = new OutputFormatterStyleStack();
    }
    public function setDecorated(bool $decorated) : void {
        $this->decorated = $decorated;
    }
    public function isDecorated() : bool {
        return $this->decorated;
    }
    public function setStyle(string $name, OutputFormatterStyleInterface $style) : void {
        $this->styles[strtolower($name)] = $style;
    }
    public function hasStyle(string $name) : bool {
        return isset($this->styles[strtolower($name)]);
    }
    public function getStyle(string $name) : OutputFormatterStyleInterface {
        if (!$this->hasStyle($name)) {
            throw new InvalidArgumentException(\sprintf('Undefined style: "%s".', $name));
        }
        return $this->styles[strtolower($name)];
    }
    public function format(?string $message) : ?string {
        return $this->formatAndWrap($message, 0);
    }
    public function formatAndWrap(?string $message, int $width) : string {
        if (null === $message) {
            return '';
        }
        $offset = 0;
        $output = '';
        $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
        $closeTagRegex = '[a-z][^<>]*+';
        $currentLineLength = 0;
        preg_match_all("#<(({$openTagRegex}) | /({$closeTagRegex})?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE);
        foreach ($matches[0] as $i => $match) {
            $pos = $match[1];
            $text = $match[0];
            if (0 != $pos && '\\' == $message[$pos - 1]) {
                continue;
            }
            // add the text up to the next tag
            $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $output, $width, $currentLineLength);
            $offset = $pos + \strlen($text);
            // opening tag?
            if ($open = '/' !== $text[1]) {
                $tag = $matches[1][$i][0];
            }
            else {
                $tag = $matches[3][$i][0] ?? '';
            }
            if (!$open && !$tag) {
                // </>
                $this->styleStack
                    ->pop();
            }
            elseif (null === ($style = $this->createStyleFromString($tag))) {
                $output .= $this->applyCurrentStyle($text, $output, $width, $currentLineLength);
            }
            elseif ($open) {
                $this->styleStack
                    ->push($style);
            }
            else {
                $this->styleStack
                    ->pop($style);
            }
        }
        $output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
        return strtr($output, [
            "\x00" => '\\',
            '\\<' => '<',
            '\\>' => '>',
        ]);
    }
    public function getStyleStack() : OutputFormatterStyleStack {
        return $this->styleStack;
    }
    
    /**
     * Tries to create new style instance from string.
     */
    private function createStyleFromString(string $string) : ?OutputFormatterStyleInterface {
        if (isset($this->styles[$string])) {
            return $this->styles[$string];
        }
        if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', $string, $matches, \PREG_SET_ORDER)) {
            return null;
        }
        $style = new OutputFormatterStyle();
        foreach ($matches as $match) {
            array_shift($match);
            $match[0] = strtolower($match[0]);
            if ('fg' == $match[0]) {
                $style->setForeground(strtolower($match[1]));
            }
            elseif ('bg' == $match[0]) {
                $style->setBackground(strtolower($match[1]));
            }
            elseif ('href' === $match[0]) {
                $url = preg_replace('{\\\\([<>])}', '$1', $match[1]);
                $style->setHref($url);
            }
            elseif ('options' === $match[0]) {
                preg_match_all('([^,;]+)', strtolower($match[1]), $options);
                $options = array_shift($options);
                foreach ($options as $option) {
                    $style->setOption($option);
                }
            }
            else {
                return null;
            }
        }
        return $style;
    }
    
    /**
     * Applies current style from stack to text, if must be applied.
     */
    private function applyCurrentStyle(string $text, string $current, int $width, int &$currentLineLength) : string {
        if ('' === $text) {
            return '';
        }
        if (!$width) {
            return $this->isDecorated() ? $this->styleStack
                ->getCurrent()
                ->apply($text) : $text;
        }
        if (!$currentLineLength && '' !== $current) {
            $text = ltrim($text);
        }
        if ($currentLineLength) {
            $prefix = substr($text, 0, $i = $width - $currentLineLength) . "\n";
            $text = substr($text, $i);
        }
        else {
            $prefix = '';
        }
        preg_match('~(\\n)$~', $text, $matches);
        $text = $prefix . $this->addLineBreaks($text, $width);
        $text = rtrim($text, "\n") . ($matches[1] ?? '');
        if (!$currentLineLength && '' !== $current && !str_ends_with($current, "\n")) {
            $text = "\n" . $text;
        }
        $lines = explode("\n", $text);
        foreach ($lines as $line) {
            $currentLineLength += \strlen($line);
            if ($width <= $currentLineLength) {
                $currentLineLength = 0;
            }
        }
        if ($this->isDecorated()) {
            foreach ($lines as $i => $line) {
                $lines[$i] = $this->styleStack
                    ->getCurrent()
                    ->apply($line);
            }
        }
        return implode("\n", $lines);
    }
    private function addLineBreaks(string $text, int $width) : string {
        $encoding = mb_detect_encoding($text, null, true) ?: 'UTF-8';
        return b($text)->toCodePointString($encoding)
            ->wordwrap($width, "\n", true)
            ->toByteString($encoding);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
OutputFormatter::$styles private property
OutputFormatter::$styleStack private property
OutputFormatter::addLineBreaks private function
OutputFormatter::applyCurrentStyle private function Applies current style from stack to text, if must be applied.
OutputFormatter::createStyleFromString private function Tries to create new style instance from string.
OutputFormatter::escape public static function Escapes &quot;&lt;&quot; and &quot;&gt;&quot; special chars in given text.
OutputFormatter::escapeTrailingBackslash public static function Escapes trailing &quot;\&quot; in given text.
OutputFormatter::format public function Formats a message according to the given styles. Overrides OutputFormatterInterface::format 1
OutputFormatter::formatAndWrap public function Formats a message according to the given styles, wrapping at `$width` (0 means no wrapping). Overrides WrappableOutputFormatterInterface::formatAndWrap
OutputFormatter::getStyle public function Gets style options from style with specified name. Overrides OutputFormatterInterface::getStyle
OutputFormatter::getStyleStack public function
OutputFormatter::hasStyle public function Checks if output formatter has style with specified name. Overrides OutputFormatterInterface::hasStyle
OutputFormatter::isDecorated public function Whether the output will decorate messages. Overrides OutputFormatterInterface::isDecorated
OutputFormatter::setDecorated public function Sets the decorated flag. Overrides OutputFormatterInterface::setDecorated
OutputFormatter::setStyle public function Sets a new style. Overrides OutputFormatterInterface::setStyle
OutputFormatter::__clone public function
OutputFormatter::__construct public function Initializes console output formatter. 1

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal