Completed
Push — master ( 79c16c...fd607f )
by Steve
01:44
created

UrlDiceGenerator::flattenDiceSets()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace MeadSteve\DiceApi;
4
5
use MeadSteve\DiceApi\Dice\Factories\DiceFactory;
6
use MeadSteve\DiceApi\Dice\Factories\NumericDiceFactory;
7
use MeadSteve\DiceApi\Dice\Factories\SpecialDiceFactory;
8
use MeadSteve\DiceApi\Dice\UncreatableDiceException;
9
10
class UrlDiceGenerator
11
{
12
    /**
13
     * @var DiceFactory
14
     */
15
    private $diceFactories = [];
16
17
    public function __construct()
18
    {
19
        $this->diceFactories[] = new NumericDiceFactory();
20
        $this->diceFactories[] = new SpecialDiceFactory();
21
    }
22
23
    public function diceFromUrlString($urlString)
24
    {
25
        $parts = explode("/", $urlString);
26
        $parts = array_filter($parts, [$this, 'notBlank']);
27
        $diceSets = array_map([$this, 'getDiceForPart'], $parts);
28
        return $this->flattenDiceSets($diceSets);
29
    }
30
31
    /**
32
     * @param string $part
33
     *
34
     * @throws UncreatableDiceException
35
     *
36
     * @return Dice[]
37
     */
38
    private function getDiceForPart($part)
39
    {
40
        $data = $this->parseDiceString($part);
41
42
        foreach ($this->diceFactories as $factory) {
0 ignored issues
show
Bug introduced by steve.brazier
The expression $this->diceFactories of type object<MeadSteve\DiceApi...\Factories\DiceFactory> is not traversable.
Loading history...
43
            if ($factory->handlesType($data["type"])) {
44
                return $factory->buildDice($data["type"], $data["count"]);
45
            }
46
        }
47
48
        throw new UncreatableDiceException("No idea how to make a d{$data['type']}");
49
    }
50
51
    /**
52
     * @param array[]
53
     * @return array
54
     */
55
    private function flattenDiceSets($diceSets)
56
    {
57
        $dice = [];
58
        foreach ($diceSets as $set) {
59
            $dice = array_merge($dice, $set);
60
        }
61
        return $dice;
62
    }
63
64
    /**
65
     * @param string $part
66
     * @return array
67
     */
68
    private function parseDiceString($part)
69
    {
70
        $data = [];
71
        $valid = preg_match("/(?P<count>[0-9]+)?d(?P<type>[^\/]+)/i", $part, $data);
72
        if (!$valid) {
73
            throw new UncreatableDiceException("Problem creating dice from incorrectly formated data: " . $part);
74
        }
75
        if (!$data["count"]) {
76
            $data["count"] = 1;
77
        }
78
        return $data;
79
    }
80
81
    private function notBlank($string)
82
    {
83
        return $string !== "";
84
    }
85
}
86