Completed
Push — master ( a0cbad...44dfcb )
by Alexander
8s
created

StringCollection::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Yandex\Common;
4
5
use Yandex\Common\Exception\InvalidArgumentException;
6
7
/**
8
 * String collection
9
 *
10
 * @category Yandex
11
 * @package  Common
12
 *
13
 * @author  Vasilii Zaluev
14
 * @created 17.03.16 22:31
15
 */
16
class StringCollection
17
{
18
    /**
19
    * This string collection will convert to one string in get request by join
20
    *
21
    * @var string
22
    */
23
    protected $collection = [];
24
25 8
    public function __construct($strings)
26
    {
27 8
        foreach ($strings as $string) {
28 8
            if (!self::isString($string)) {
29 1
                throw new InvalidArgumentException('Argument must have only strings');
30
            }
31
32 7
            $this->collection[] = $string;
33 7
        }
34 7
    }
35
36
    /**
37
    * @param $strings
38
    * @return null|self
39
    * @throws InvalidArgumentException
40
    */
41 11
    public static function init($strings)
42
    {
43 11
        if (is_null($strings)) {
44 2
            return null;
45
        }
46
47 10
        if (self::isString($strings)) {
48 3
            return new static([$strings]);
49
        }
50
51 8
        if (is_array($strings)) {
52 7
            if (empty($strings)) {
53 1
                return null;
54
            }
55
56 6
            return new self($strings);
57
        }
58
59 1
        throw new InvalidArgumentException('Argument must be string or string list ' . gettype($strings) . ' received');
60
    }
61
62 3
    public function getAll()
63
    {
64 3
        return implode(',', $this->collection);
65
    }
66
67 10
    private static function isString($string)
68
    {
69 10
        return is_string($string) || method_exists($string, '__toString');
70
    }
71
72 4
    public function asArray()
73
    {
74 4
        return $this->collection;
75
    }
76
}
77