summaryrefslogtreecommitdiff
path: root/src/Manager/ScormDisk.php
blob: 249f02718415d9463578a32bfbef41c32c62785a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace Peopleaps\Scorm\Manager;

use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use Peopleaps\Scorm\Exception\StorageNotFoundException;
use ZipArchive;

class ScormDisk
{
    /**
     * Extract zip file into destination directory.
     *
     * @param string $path Destination directory
     * @param string $zipFilePath The path to the zip file.
     *
     * @return bool True on success, false on failure.
     */
    public function unzip($file, $path)
    {
        $path = $this->cleanPath($path);

        $zipArchive = new ZipArchive();
        if ($zipArchive->open($file) !== true) {
            return false;
        }

        /** @var FilesystemAdapter $disk */
        $disk = $this->getDisk();

        for ($i = 0; $i < $zipArchive->numFiles; ++$i) {
            $zipEntryName = $zipArchive->getNameIndex($i);
            $destination = $path . DIRECTORY_SEPARATOR . $this->cleanPath($zipEntryName);
            if ($this->isDirectory($zipEntryName)) {
                $disk->createDir($destination);
                continue;
            }
            $disk->putStream($destination, $zipArchive->getStream($zipEntryName));
        }

        return true;
    }

    /**
     * @param string $directory
     * @return bool
     */
    public function deleteScormFolder($folderHashedName)
    {
        return $this->getDisk()->deleteDirectory($folderHashedName);
    }

    private function isDirectory($zipEntryName)
    {
        return substr($zipEntryName, -1) ===  '/';
    }

    private function cleanPath($path)
    {
        return str_replace('/', DIRECTORY_SEPARATOR, $path);
    }

    /**
     * @return FilesystemAdapter $disk
     */
    private function getDisk()
    {
        if (!config()->has('filesystems.disks.' . config('scorm.disk'))) {
            throw new StorageNotFoundException('scorm_disk_not_define');
        }
        return Storage::disk(config('scorm.disk'));
    }
}