Completed
Push — master ( 90b7b2...d5b357 )
by Steve
03:23
created

DiceGenerator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 7
Bugs 0 Features 2
Metric Value
wmc 12
c 7
b 0
f 2
lcom 0
cbo 3
dl 0
loc 70
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A diceFromUrlString() 0 7 1
A getDiceForPart() 0 12 4
A newDiceOfSize() 0 7 2
A flattenDiceSets() 0 8 2
A parseDiceString() 0 13 3
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
        $parts = array_filter($parts, function($part) {return $part !== "";});
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 = $this->parseDiceString($part);
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
        return $newDice;
33
    }
34
35
    /**
36
     * @param $size
37
     * @return Dice
38
     */
39
    private function newDiceOfSize($size)
40
    {
41
        if ($size == 0) {
42
            return new ZeropointDice();
43
        }
44
        return new BasicDice($size);
45
    }
46
47
    /**
48
     * @param array[]
49
     * @return array
50
     */
51
    private function flattenDiceSets($diceSets)
52
    {
53
        $dice = [];
54
        foreach ($diceSets as $set) {
55
            $dice = array_merge($dice, $set);
56
        }
57
        return $dice;
58
    }
59
60
    /**
61
     * @param string $part
62
     * @return array
63
     */
64
    private function parseDiceString($part)
65
    {
66
        $data = [];
67
        $valid = preg_match("/(?P<count>[0-9]+)?d(?P<size>[0-9]+)/i", $part, $data);
68
        if (!$valid) {
69
            throw new UncreatableDiceException("Problem creating dice from incorrectly formated data: " + $part);
70
        }
71
        if (!$data["count"]) {
72
            $data["count"] = 1;
73
        }
74
        return $data;
75
76
    }
77
}
78