Add ansi color codes to console output
[bdrem.git] / src / bdrem / Renderer / Console.php
1 <?php
2 namespace bdrem;
3
4 class Renderer_Console
5 {
6     /**
7      * Use ANSI color codes for output coloring
8      *
9      * @var boolean
10      */
11     public $ansi = true;
12
13     /**
14      * @var \Console_Color2
15      */
16     protected $cc;
17
18     public function render($arEvents)
19     {
20         if ($this->ansi) {
21             $this->cc = new \Console_Color2();
22         }
23
24         $tbl = new \Console_Table(
25             CONSOLE_TABLE_ALIGN_LEFT,
26             array('sect' => '', 'rule' => '-', 'vert' => ''),
27             1, null, $this->ansi
28         );
29         $tbl->setAlign(0, CONSOLE_TABLE_ALIGN_RIGHT);
30         $tbl->setAlign(1, CONSOLE_TABLE_ALIGN_RIGHT);
31
32         $tbl->setHeaders(
33             $this->ansiWrap(
34                 array('Days', 'Age', 'Name', 'Event', 'Date', 'Day'),
35                 '%_%9'
36             )
37         );
38         $tbl->setBorderVisibility(
39             array(
40                 'left'   => false,
41                 'right'  => false,
42                 'top'    => true,
43                 'bottom' => false,
44                 'inner'  => true,
45             )
46         );
47
48         foreach ($arEvents as $event) {
49             $colorCode = null;
50             if ($event->days == 0) {
51                 $colorCode = '%R';
52             }
53             $tbl->addRow(
54                 $this->ansiWrap(
55                     array(
56                         $event->days,
57                         $event->age,
58                         wordwrap($event->title, 30, "\n", true),
59                         wordwrap($event->type, 20, "\n", true),
60                         $event->date,
61                         strftime('%a', strtotime($event->localDate))
62                     ),
63                     $colorCode
64                 )
65             );
66         }
67         return $tbl->getTable();
68     }
69
70     protected function ansiWrap($data, $colorCode = null)
71     {
72         if (!$this->ansi || $colorCode === null) {
73             return $data;
74         }
75
76         foreach ($data as $k => &$value) {
77             $value = $this->cc->convert(
78                 $colorCode . $value . '%n'
79             );
80         }
81         return $data;
82     }
83 }
84 ?>