Completed
Pull Request — master (#3)
by Harry
07:29
created

FileNodeCollection::getCommonPrefixString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
crap 3
1
<?php
2
/**
3
 * This file is part of graze/data-file
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/data-file/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/data-file
12
 */
13
14
namespace Graze\DataFile\Node;
15
16
use Graze\DataNode\NodeCollection;
17
use InvalidArgumentException;
18
19
/**
20 3
 * Class FileNodeCollection
21
 *
22 3
 * @package Graze\DataFile\Node\File
23 1
 */
24
class FileNodeCollection extends NodeCollection implements FileNodeCollectionInterface
25
{
26 2
    /**
27 2
     * For a given set of files, return any common prefix (i.e. directory, s3 key)
28 2
     *
29
     * @return string|null
30 2
     */
31 2
    public function getCommonPrefix()
32
    {
33 2
        if ($this->count() == 0) {
34
            return null;
35
        }
36
37
        $commonPath = $this->reduce(function ($commonPath, FileNodeInterface $file) {
38
            if (is_null($commonPath)) {
39
                return $file->getPath();
40
            }
41
            return $this->getCommonPrefixString($commonPath, $file->getPath());
42 2
        });
43
44 2
        return (strlen($commonPath) > 0) ? $commonPath : null;
45 2
    }
46 2
47
    /**
48 2
     * @param string $left
49 1
     * @param string $right
50
     *
51
     * @return string
52
     */
53
    private function getCommonPrefixString($left, $right)
54
    {
55 17
        for ($i = 1; $i < strlen($left); $i++) {
56
            if (substr_compare($left, $right, 0, $i) !== 0) {
57 17
                return substr($left, 0, $i - 1);
58 1
            }
59
        }
60 16
        return substr($left, 0, $i);
61
    }
62
63
    /**
64
     * @param mixed $value
65
     *
66
     * @return $this
67
     */
68
    public function add($value)
69
    {
70
        if (!($value instanceof FileNodeInterface)) {
71
            throw new InvalidArgumentException("The specified value does not implement FileNodeInterface");
72
        }
73
        return parent::add($value);
74
    }
75
}
76