Yii2: Incorrect background color generation in BaseConsole::renderColoredString()

Created on 4 Jan 2017  路  2Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

  1. Create a new command:
<?php
namespace app\commands;

use yii\console\Controller;
use yii\helpers\BaseConsole;

class ColorTestController extends Controller
{
    public function actionIndex()
    {
        list($width, $height) = BaseConsole::getScreenSize(true);

        $foregrounds = [null, 'k', 'K', 'r', 'R', 'g', 'G', 'y', 'Y', 'b', 'B', 'm', 'M', 'p', 'P', 'c', 'C', 'w', 'W'];

        $backgrounds = [null, '0', '1', '2', '3', '4', '5', '6', '7'];

        $difference = intval(floor($width / 24));

        for ($min = 0; $min < 9; $min += $difference) {
            $max = $min + $difference;

            foreach ($foregrounds as $foreground) {
                foreach ($backgrounds as $key => $background) {
                    if ($key < $min || $key >= $max) {
                        continue;
                    }

                    $this->stdout(BaseConsole::renderColoredString(sprintf(
                        '%2s %2s %s%s%s',
                        is_null($foreground) ? '' : '%%' . $foreground,
                        is_null($background) ? '' : '%%' . $background,
                        is_null($foreground) ? '' : '%' . $foreground,
                        is_null($background) ? '' : '%' . $background,
                        'Sample Text%n       '
                    )));
                }

                $this->stdout("\n");
            }

            $this->stdout("\n\n");
        }
    }
}
  1. Run ./console color-test

What is the expected result?

  • The Sample text in %W %0 Sample Text has white color and black background
  • The Sample text in %W %6 Sample Text has white color and cyan background
  • The Sample text in %W %7 Sample Text has white color and gray background

What do you get instead?

  • The Sample text in %W %0 Sample Text has white color and gray background
  • The Sample text in %W %6 Sample Text has white color and purple background
  • The Sample text in %W %7 Sample Text has white color and cyan background

Additional info

| Q | A
| ---------------- | ---
| Yii version | any 2.* released after Mar 23, 2014
| PHP version | any
| Operating system | any

How to fix

In the BaseConsole::renderColoredString() method, change these $conversions array values:

  • '%0' => [self::BG_GREY] to '%0' => [self::BG_BLACK]
  • '%6' => [self::BG_PURPLE] to '%6' => [self::BG_CYAN]
  • '%7' => [self::BG_CYAN] to '%7' => [self::BG_GREY]
bug

Most helpful comment

Thank you for a perfect report.
It was really easy and pleasant to reproduce and fix the problem.

All 2 comments

Thank you for a perfect report.
It was really easy and pleasant to reproduce and fix the problem.

Many thanks for both a praise and a fix. :)

Was this page helpful?
0 / 5 - 0 ratings