sfFormatter.class.php 2.47 KB
Newer Older
Игорь's avatar
init    
Игорь committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * sfFormatter provides methods to format text to be displayed on a console.
 *
 * @package    symfony
 * @subpackage command
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfFormatter.class.php 21908 2009-09-11 12:06:21Z fabien $
 */
class sfFormatter
{
  protected
    $size = null;

  function __construct($maxLineSize = null)
  {
    if (null === $maxLineSize)
    {
      // this is tricky because "tput cols 2>&1" is not accurate
      $maxLineSize = ctype_digit(trim(shell_exec('tput cols 2>&1'))) ? (integer) shell_exec('tput cols') : 78;
    }

    $this->size = $maxLineSize;
  }

  /**
   * Sets a new style.
   *
   * @param string $name    The style name
   * @param array  $options An array of options
   */
  public function setStyle($name, $options = array())
  {
  }

  /**
   * Formats a text according to the given parameters.
   *
   * @param  string $text         The test to style
   * @param  mixed  $parameters   An array of parameters
   *
   * @return string The formatted text
   */
  public function format($text = '', $parameters = array())
  {
    return $text;
  }

  /**
   * Formats a message within a section.
   *
   * @param string  $section  The section name
   * @param string  $text     The text message
   * @param integer $size     The maximum size allowed for a line
   */
  public function formatSection($section, $text, $size = null)
  {
    if (!$size)
    {
      $size = $this->size;
    }

    $section = sprintf('>> %-9s ', $section);

    return $section.$this->excerpt($text, $size - strlen($section));
  }

  /**
   * Truncates a line.
   *
   * @param string  $text The text
   * @param integer $size The maximum size of the returned string
   *
   * @return string The truncated string
   */
  public function excerpt($text, $size = null)
  {
    if (!$size)
    {
      $size = $this->size;
    }

    if (strlen($text) < $size)
    {
      return $text;
    }

    $subsize = floor(($size - 3) / 2);

    return substr($text, 0, $subsize).'...'.substr($text, -$subsize);
  }

  /**
   * Sets the maximum line size.
   *
   * @param integer $size The maximum line size for a message
   */
  public function setMaxLineSize($size)
  {
    $this->size = $size;
  }
}