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

DiceGenerator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 11
c 5
b 0
f 2
lcom 0
cbo 3
dl 0
loc 57
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A diceFromUrlString() 0 6 1
B getDiceForPart() 0 18 6
A newDiceOfSize() 0 7 2
A flattenDiceSets() 0 8 2
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