Completed
Push — master ( 8677c5...0f9d3b )
by Orkhan
02:31
created

ZipContent::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Orkhanahmadov\ZipValidator\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Http\UploadedFile;
7
use Illuminate\Support\Collection;
8
use Orkhanahmadov\ZipValidator\Exceptions\ZipException;
9
10
class ZipContent implements Rule
11
{
12
    /**
13
     * @var Collection
14
     */
15
    private $files;
16
    /**
17
     * @var Collection
18
     */
19
    private $failedFiles;
20
21
    /**
22
     * Create a new rule instance.
23
     *
24
     * @param array|string $files
25
     */
26
    public function __construct($files)
27
    {
28
        $this->files = is_array($files) ? collect($files) : collect(func_get_args());
29
    }
30
31
    /**
32
     * Determine if the validation rule passes.
33
     *
34
     * @param string $attribute
35
     * @param UploadedFile $zip
36
     * @return bool
37
     */
38
    public function passes($attribute, $zip): bool
39
    {
40
        $content = $this->readContent($zip);
41
42
        $this->failedFiles = $this->files->reject(function ($file) use ($content) {
43
            return $content->contains($file);
44
        });
45
46
        return ! $this->failedFiles->count();
47
    }
48
49
    /**
50
     * Reads ZIP file content and returns collection with result.
51
     *
52
     * @param UploadedFile $value
53
     * @return Collection
54
     */
55
    private function readContent(UploadedFile $value): Collection
56
    {
57
        $zip = zip_open($value->path());
58
59
        throw_unless(!is_int($zip), new ZipException($zip));
60
61
        $content = collect();
62
        while ($file = zip_read($zip)) {
63
            $content->add(zip_entry_name($file));
64
        }
65
66
        zip_close($zip);
67
68
        return $content;
69
    }
70
71
    /**
72
     * Get the validation error message.
73
     *
74
     * @return string
75
     */
76
    public function message(): string
77
    {
78
        return __('zipValidator::messages.not_found', [
79
            'files' => $this->failedFiles->implode(', '),
80
        ]);
81
    }
82
}
83