Completed
Pull Request — master (#27)
by
unknown
02:22
created

AsciiArtItemJustificationHelper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 71
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A justifyRow() 0 12 4
A leftJustifyRow() 0 4 1
A rightJustifyRow() 0 7 1
A centerJustifyRow() 0 9 1
A _getPadding() 0 5 1
1
<?php
2
namespace PhpSchool\CliMenu\MenuItem\Helper;
3
4
use PhpSchool\CliMenu\MenuItem\AsciiArtItem;
5
6
class AsciiArtItemJustificationHelper
7
{
8
    private $contentWidth;
9
    private $artLength;
10
    private $position;
11
12
    public function  __construct($position, $contentWidth, $artLength)
13
    {
14
        $this->contentWidth = $contentWidth;
15
        $this->artLength = $artLength;
16
        $this->position = $position;
17
    }
18
19
    public function justifyRow($row)
20
    {
21
        switch ($this->position) {
22
            case AsciiArtItem::POSITION_LEFT:
23
                return $this->leftJustifyRow($row);
24
            case AsciiArtItem::POSITION_RIGHT:
25
                return $this->rightJustifyRow($row);
26
            case AsciiArtItem::POSITION_CENTER:
27
            default:
28
                return $this->centerJustifyRow($row);
29
        }
30
    }
31
32
    /**
33
     * @param $row
34
     * @return string
35
     */
36
    private function leftJustifyRow($row)
37
    {
38
        return $row;
39
    }
40
41
    /**
42
     * @param $row
43
     * @return string
44
     */
45
    private function rightJustifyRow($row)
46
    {
47
        $padding = $this->_getPadding($row);
48
        $row = rtrim($row);
49
        $padding = $padding - ($this->artLength - mb_strlen($row));
50
        return sprintf('%s%s', str_repeat(' ', $padding), $row);
51
    }
52
53
    /**
54
     * @param $row
55
     * @return string
56
     */
57
    private function centerJustifyRow($row)
58
    {
59
        $padding = $this->_getPadding($row);
60
        $row = rtrim($row);
61
        $padding = $padding - ($this->artLength - mb_strlen($row));
62
        $left = ceil($padding / 2);
63
        $right = $padding - $left;
64
        return sprintf('%s%s%s', str_repeat(' ', $left), $row, str_repeat(' ', $right));
65
    }
66
67
    /**
68
     * @param $row
69
     * @return int
70
     */
71
    private function _getPadding($row)
72
    {
73
        $length = mb_strlen($row);
74
        return $this->contentWidth - $length;
75
    }
76
}