Completed
Push — master ( 6bb539...9dcb59 )
by Steve
03:16
created

DiceGenerator::flattenDiceSets()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4286
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace MeadSteve\DiceApi\Dice;
4
5
use MeadSteve\DiceApi\BasicDice;
6
use MeadSteve\DiceApi\Dice;
7
8
9
class DiceGenerator
10
{
11
    public function diceFromUrlString($urlString)
12
    {
13
        $parts = explode("/", $urlString);
14
        $diceSets = array_map([$this, 'getDiceForPart'], $parts);
15
        return $this->flattenDiceSets($diceSets);
16
    }
17
18
    /**
19
     * @param string $part
20
     * @return Dice[]
21
     */
22
    private function getDiceForPart($part)
23
    {
24
        $newDice = [];
25
        $data = [];
26
        $valid = preg_match("/(?P<count>[0-9]+)?d(?P<size>[0-9]+)/i", $part, $data);
27
        if ($valid) {
28
            if ((strlen($data["size"]) > 4) || ($data["size"] > 9000)) {
29
                throw new UncreatableDiceException("Only dice with a power level less than 9000 can be created.");
30
            }
31
            if (!$data["count"]) {
32
                $data["count"] = 1;
33
            }
34
            for ($i = 0; $i < $data["count"]; $i++) {
35
                $newDice[] = $this->newDiceOfSize($data["size"]);
36
            }
37
        }
38
        return $newDice;
39
    }
40
41
    /**
42
     * @param $size
43
     * @return Dice
44
     */
45
    private function newDiceOfSize($size)
46
    {
47
        if ($size == 0) {
48
            return new ZeropointDice();
49
        }
50
        return new BasicDice($size);
51
    }
52
53
    /**
54
     * @param array[]
55
     * @return array
56
     */
57
    private function flattenDiceSets($diceSets)
58
    {
59
        $dice = [];
60
        foreach ($diceSets as $set) {
61
            $dice = array_merge($dice, $set);
62
        }
63
        return $dice;
64
    }
65
}
66