Completed
Push — master ( 9dcb59...90b7b2 )
by Steve
03:39
created

DiceGenerator::parseDiceString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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