Passed
Push — master ( 81b80f...db2b61 )
by Dan
04:29
created

Usher::addWordToMask()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5.0291

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 31
ccs 17
cts 19
cp 0.8947
rs 8.439
c 1
b 0
f 0
cc 5
eloc 19
nc 5
nop 5
crap 5.0291
1
<?php
2
3
namespace SixtyNine\Cloud\Usher;
4
5
use Imagine\Image\Point;
6
use SixtyNine\Cloud\Drawer\Drawer;
7
use SixtyNine\Cloud\Factory\Logger;
8
use SixtyNine\Cloud\FontMetrics;
9
use SixtyNine\Cloud\Model\Box;
10
use SixtyNine\Cloud\Placer\PlacerInterface;
11
12
/**
13
 * Responsible to find a place for the word in the cloud
14
 */
15
16
class Usher
17
{
18
    const DEFAULT_MAX_TRIES = 100000;
19
20
    /** @var int */
21
    protected $maxTries;
22
23
    /** @var \SixtyNine\Cloud\Usher\MaskInterface */
24
    protected $mask;
25
26
    /** @var \SixtyNine\Cloud\Placer\PlacerInterface */
27
    protected $placer;
28
29
    /** @var \SixtyNine\Cloud\FontMetrics */
30
    protected $metrics;
31
32
    /** @var Logger */
33
    protected $logger;
34
35
    /**
36
     * @param int $imgWidth
37
     * @param int $imgHeight
38
     * @param PlacerInterface $placer
39
     * @param FontMetrics $metrics
40
     * @param int $maxTries
41
     */
42 6
    public function __construct(
43
        $imgWidth,
44
        $imgHeight,
45
        PlacerInterface $placer,
46
        FontMetrics $metrics,
47
        $maxTries = self::DEFAULT_MAX_TRIES
48
    ) {
49 6
        $this->mask = new QuadTreeMask($imgWidth, $imgHeight);
50 6
        $this->metrics = $metrics;
51 6
        $this->imgHeight = $imgHeight;
0 ignored issues
show
Bug introduced by
The property imgHeight does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
52 6
        $this->imgWidth = $imgWidth;
0 ignored issues
show
Bug introduced by
The property imgWidth does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
53 6
        $this->maxTries = $maxTries;
54 6
        $this->placer = $placer;
55 6
        $this->logger = Logger::getInstance();
56 6
    }
57
58
    /**
59
     * @param string $word
60
     * @param string $font
61
     * @param int $size
0 ignored issues
show
Bug introduced by
There is no parameter named $size. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
62
     * @param int $angle
63
     * @return bool|Box
64
     */
65 6
    public function getPlace($word, $font, $fontSize, $angle, $precise = false)
66
    {
67 6
        $this->logger->log(
68
            sprintf(
69 6
                'Search place for "%s", font = %s(%s), angle = %s',
70
                $word,
71 6
                str_replace('.ttf', '', $font),
72
                $fontSize,
73
                $angle
74
            ),
75 6
            Logger::DEBUG
76
        );
77
78 6
        $bounds = new Box(0, 0, $this->imgWidth, $this->imgHeight);
79 6
        $size = $this->metrics->calculateSize($word, $font, $fontSize);
80 6
        $box = Drawer::getBoxFoxText(0, 0, $size->getWidth(), $size->getHeight(), $angle);
81
82 6
        $this->logger->log('  Text dimensions: ' . $size->getDimensions(), Logger::DEBUG);
83
84 6
        $place = $this->searchPlace($bounds, $box);
85
86 6
        if ($place) {
87 6
            if ($precise) {
88 1
                $this->addWordToMask($word, $place, $font, $fontSize, $angle);
89
            } else {
90 5
                $this->mask->add(new Point(0, 0), $place, $angle);
0 ignored issues
show
Unused Code introduced by
The call to MaskInterface::add() has too many arguments starting with $angle.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
91
            }
92 6
            return $place;
93
        }
94
95
        return false;
96
    }
97
98 1
    public function addWordToMask($word, Box $place, $font, $size, $angle)
99
    {
100 1
        $base = $this->metrics->calculateSize($word, $font, $size, $angle);
101 1
        foreach (str_split($word) as $letter) {
102 1
            $box = $this->metrics->calculateSize($letter, $font, $size);
103
104 1
            if ($angle === 0) {
105 1
                $newPos = new Point($place->getX(), $place->getY() + ($base->getHeight() - $box->getHeight()));
106 1
                $this->mask->add($newPos, $box, $angle);
0 ignored issues
show
Unused Code introduced by
The call to MaskInterface::add() has too many arguments starting with $angle.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
107 1
                $place = $place->move($box->getWidth(), 0);
108
            } else {
109
                // Invert width and height
110 1
                $box = new Box(0, 0, $box->getHeight(), $box->getWidth());
111
112 1
                if ($place->getY() + ($base->getHeight() - $box->getHeight()) < 0) {
113
                    continue;
114
                }
115
116 1
                if ($place->getX() + ($base->getWidth() - $box->getWidth()) < 0) {
117
                    continue;
118
                }
119
120 1
                $newPos = new Point(
121 1
                    $place->getX() + ($base->getWidth() - $box->getWidth()),
122 1
                    $place->getY() + ($base->getHeight() - $box->getHeight())
123
                );
124 1
                $this->mask->add($newPos, $box, $angle);
0 ignored issues
show
Unused Code introduced by
The call to MaskInterface::add() has too many arguments starting with $angle.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
125 1
                $place = $place->move(0, -$box->getHeight());
126
            }
127
        }
128 1
    }
129
130
    /**
131
     * Search a free place for a new box.
132
     * @param \SixtyNine\Cloud\Model\Box $bounds
133
     * @param \SixtyNine\Cloud\Model\Box $box
134
     * @return bool|Box
135
     */
136 6
    protected function searchPlace(Box $bounds, Box $box)
137
    {
138
139 6
        $this->logger->log('  Search place for ' . $box, Logger::DEBUG);
140
141 6
        $placeFound = false;
142 6
        $current = $this->placer->getFirstPlaceToTry();
143 6
        $curTry = 1;
144
145 6
        while (!$placeFound) {
146
147 6
            if (!$current) {
148
                return false;
149
            }
150
151 6
            if ($curTry > $this->maxTries) {
152
                return false;
153
            }
154
155 6
            $currentBox = $box->move($current->getX(), $current->getY());
156
157 6
            $outOfBounds = !$currentBox->inside($bounds);
158
159 6
            if (!$outOfBounds) {
160 6
                $placeFound = !$this->mask->overlaps($currentBox);
161 6
                $placeFound = $placeFound && !$outOfBounds;
162
            }
163
164 6
            $this->logger->log(sprintf(
165 6
                '  Trying %s --> %s',
166
                $currentBox,
167 6
                $outOfBounds ? 'Out of bounds' : ($placeFound ? 'OK' : 'Collision')
168 6
            ), Logger::DEBUG);
169
170 6
            if ($placeFound) {
171 6
                break;
172
            }
173
174 6
            $current = $this->placer->getNextPlaceToTry($current);
175 6
            $curTry++;
176
        }
177
178 6
        return $currentBox->inside($bounds) ? $currentBox : false;
0 ignored issues
show
Bug introduced by
The variable $currentBox does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
179
    }
180
181 2
    public function getMask()
182
    {
183 2
        return $this->mask;
184
    }
185
}
186