Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Any way to conditionally format the data in a column? #6

Closed
johnclearyconsulting opened this issue May 22, 2023 · 4 comments
Closed

Comments

@johnclearyconsulting
Copy link

I would love a way to be able to configure very basic conditional formatting, so I could have a 'positive value' colour and a 'negative value' colour when displaying a number. Is this possible do you know?

@jc21
Copy link
Owner

jc21 commented Jun 6, 2023

Hey yep you can do this with your own manipulator:

class MyManipulator extends CliTableManipulator {
	public function colorNumber($value)
	{
		if ($value == 0) {
		    // default color
		    return $value;
		} else if ($value >= 0) {
		    // green
		    return chr(27) . '[1;32m' . $value . chr(27).'[0m';
		} else {
		    // red
		    return chr(27) . '[1;31m' . $value . chr(27).'[0m';
		}
	}
}

$table = new CliTable;
$table->setTableColor('blue');
$table->setHeaderColor('cyan');
$table->addField('First Name', 'firstName', false, 'white');
$table->addField('Last Name', 'lastName', false, 'white');
$table->addField('Number', 'numberColumn', new MyManipulator('colorNumber'));
$table->injectData($data);
$table->display();

@johnclearyconsulting
Copy link
Author

Awesome. Thanks so much for taking the time to respond! 🎉

@conrad10781
Copy link
Contributor

@jc21 , I'm not sure if you'll see this comment given the issue is closed, but I followed the above code , and am getting an unexpected output:

Screenshot from 2023-09-01 09-15-33

In my code, I pass the default value back if it's >= 5 && <= 5, but outside that it's the same code. The issue seems to be related to https://github.com/jc21/clitable/blob/master/src/jc21/CliTable.php#L403 where since we're passing back the extra color "information", mb_strwidth is showing significantly larger values.

If I update that line to:

$c = chr(27);
$fieldLength  = mb_strwidth(preg_replace("/({$c}\[(.*?)m)/", '', $field)) + 1;

I get a consistent column width, and even though $fieldLength appears to be reporting the correct values, the width of the columns are larger than expected.

Screenshot from 2023-09-01 10-26-50

versus the width with the code out of the box ( notice the padding width of the columns that previously had the colors from the Manipulator ) :

Screenshot from 2023-09-01 10-27-42

@conrad10781
Copy link
Contributor

Nevermind, I see https://github.com/jc21/clitable/blob/master/src/jc21/CliTable.php#L354 plays a role in the length as well. Will submit a PR.

conrad10781 added a commit to conrad10781/clitable that referenced this issue Sep 1, 2023
Fixed issue with dynamic colors in jc21#6
This was referenced Sep 1, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants