Rotator::getDriver()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 3
1
<?php
2
3
namespace LeadThread\Shortener\Rotators\Service;
4
5
use Exception;
6
use LeadThread\Shortener\Interfaces\UrlShortener;
7
use LeadThread\Shortener\Exceptions\ShortenerException;
8
use LeadThread\Shortener\Drivers\Bitly;
9
use LeadThread\Shortener\Drivers\Google;
10
11
class Rotator implements UrlShortener
12
{
13
    protected $drivers = [];
14
    protected $error;
15
16 30
    public function __construct(array $services){
17 30
        foreach ($services as $service) {
18 30
            if($service instanceof UrlShortener){
19 21
                $this->drivers[] = $service;
20 30
            } else if(is_string($service)) {
21 9
                $this->drivers[] = $this->getDriver($service);
22 6
            } else {
23
                throw new Exception("Could not get driver! Incorrect datatype!");
24
            }
25 27
        }
26 27
    }
27
28 9
    protected function getDriver($service){
29
        switch($service){
30 9
            case 'google':
31 6
                return new Google();
32 9
            case 'bitly':
33 6
                return new Bitly();
34 3
            default:
35 3
                throw new ShortenerException("Service is not supported! ({$service})");
36 3
        }
37
    }
38
39 21 View Code Duplication
    public function shorten($url, $encode = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40
    {
41 21
        $short = false;
42
43 21
        foreach ($this->drivers as $driver) {
44 21
            if(!is_string($short)){
45
                try {
46 21
                    $short = $driver->shorten($url, $encode);
47 21
                } catch (Exception $e) {
48 9
                    $this->error = $e;
49
                }
50 21
            }
51 21
        }
52
53 21
        if(is_string($short)){
54 15
            return $short;
55
        } else {
56 6
            throw $this->error;
57
        }
58
    }
59
}