Completed
Pull Request — master (#5)
by Dan
03:24
created

Usher::getPlace()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 32
ccs 14
cts 16
cp 0.875
rs 8.8571
c 1
b 0
f 0
cc 3
eloc 21
nc 3
nop 5
crap 3.0175
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 5
    public function __construct(
43
        $imgWidth,
44
        $imgHeight,
45
        PlacerInterface $placer,
46
        FontMetrics $metrics,
47
        $maxTries = self::DEFAULT_MAX_TRIES
48
    ) {
49 5
        $this->mask = new QuadTreeMask($imgWidth, $imgHeight);
50 5
        $this->metrics = $metrics;
51 5
        $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 5
        $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 5
        $this->maxTries = $maxTries;
54 5
        $this->placer = $placer;
55 5
        $this->logger = Logger::getInstance();
56 5
    }
57
58
    /**
59
     * @param string $word
60
     * @param string $font
61
     * @param int $size
62
     * @param int $angle
63
     * @return bool|Box
64
     */
65 5
    public function getPlace($word, $font, $size, $angle, $precise = false)
66
    {
67 5
        $this->logger->log(
68
            sprintf(
69 5
                'Search place for "%s", font = %s(%s), angle = %s',
70
                $word,
71 5
                str_replace('.ttf', '', $font),
72
                $size,
73
                $angle
74
            ),
75 5
            Logger::DEBUG
76
        );
77
78 5
        $bounds = new Box(0, 0, $this->imgWidth, $this->imgHeight);
79 5
        $size = $this->metrics->calculateSize($word, $font, $size);
80 5
        $box = Drawer::getBoxFoxText(0, 0, $size->getWidth(), $size->getHeight(), $angle);
81
82 5
        $this->logger->log('  Text dimensions: ' . $size->getDimensions(), Logger::DEBUG);
83
84 5
        $place = $this->searchPlace($bounds, $box);
85
86 5
        if ($place) {
87 5
            if ($precise) {
88
                $this->addWordToMask($word, $place, $font, $size, $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 5
            return $place;
93
        }
94
95
        return false;
96
    }
97
98
    public function addWordToMask($word, Box $place, $font, $size, $angle)
99
    {
100
        $base = $this->metrics->calculateSize($word, $font, $size, $angle);
101
        foreach (str_split($word) as $letter) {
102
            $box = $this->metrics->calculateSize($letter, $font, $size);
103
            $newPos = new Point($place->getX(), $place->getY() + ($base->getHeight() - $box->getHeight()));
104
            $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...
105
106
            if ($angle === 0) {
107
                $place = $place->move($box->getWidth(), 0);
108
            } else {
109
                // FIXME: this is wrong
110
                $place = $place->move(0, $box->getHeight());
111
            }
112
        }
113
    }
114
115
    /**
116
     * Search a free place for a new box.
117
     * @param \SixtyNine\Cloud\Model\Box $bounds
118
     * @param \SixtyNine\Cloud\Model\Box $box
119
     * @return bool|Box
120
     */
121 5
    protected function searchPlace(Box $bounds, Box $box)
122
    {
123
124 5
        $this->logger->log('  Search place for ' . $box, Logger::DEBUG);
125
126 5
        $placeFound = false;
127 5
        $current = $this->placer->getFirstPlaceToTry();
128 5
        $curTry = 1;
129
130 5
        while (!$placeFound) {
131
132 5
            if (!$current) {
133
                return false;
134
            }
135
136 5
            if ($curTry > $this->maxTries) {
137
                return false;
138
            }
139
140 5
            $currentBox = $box->move($current->getX(), $current->getY());
141
142 5
            $outOfBounds = !$currentBox->inside($bounds);
143
144 5
            if (!$outOfBounds) {
145 5
                $placeFound = !$this->mask->overlaps($currentBox);
146 5
                $placeFound = $placeFound && !$outOfBounds;
147
            }
148
149 5
            $this->logger->log(sprintf(
150 5
                '  Trying %s --> %s',
151
                $currentBox,
152 5
                $outOfBounds ? 'Out of bounds' : ($placeFound ? 'OK' : 'Collision')
153 5
            ), Logger::DEBUG);
154
155 5
            if ($placeFound) {
156 5
                break;
157
            }
158
159 5
            $current = $this->placer->getNextPlaceToTry($current);
160 5
            $curTry++;
161
        }
162
163 5
        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...
164
    }
165
166 1
    public function getMask()
167
    {
168 1
        return $this->mask;
169
    }
170
}
171