ZipAssetsService::download()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 46
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3

Importance

Changes 8
Bugs 1 Features 2
Metric Value
c 8
b 1
f 2
dl 0
loc 46
ccs 18
cts 18
cp 1
rs 8.9411
cc 3
eloc 17
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Craft;
4
5
/**
6
 * Zip Assets Service.
7
 *
8
 * Contains plugin logics.
9
 *
10
 * @author    Bob Olde Hampsink <[email protected]>
11
 * @copyright Copyright (c) 2016, Bob Olde Hampsink
12
 *
13
 * @link      http://github.com/boboldehampsink
14
 */
15
class ZipAssetsService extends BaseApplicationComponent
16
{
17
    /**
18
     * Download zipfile.
19
     *
20
     * @param array  $files
21
     * @param string $filename
22
     *
23
     * @return string
24
     */
25 2
    public function download($files, $filename)
26
    {
27
        // Get assets
28 2
        $criteria = craft()->elements->getCriteria(ElementType::Asset);
29 2
        $criteria->id = $files;
30 2
        $criteria->limit = null;
31 2
        $assets = $criteria->find();
32
33
        // Set destination zip
34 2
        $destZip = craft()->path->getTempPath().$filename.'_'.time().'.zip';
35
36
        // Create zip
37 2
        $zip = new \ZipArchive();
38
39
        // Open zip
40 2
        if ($zip->open($destZip, $zip::CREATE) === true) {
41
42
            // Loop through assets
43 1
            foreach ($assets as $asset) {
44
45
                // Get asset source
46 1
                $source = $asset->getSource();
47
48
                 // Get asset source type
49 1
                $sourceType = $source->getSourceType();
50
51
                // Get asset file
52 1
                $file = $sourceType->getLocalCopy($asset);
53
54
                // Add to zip
55 1
                $zip->addFromString($asset->filename, IOHelper::getFileContents($file));
56
57
                // Remove the file
58 1
                IOHelper::deleteFile($file);
59 1
            }
60
61
            // Close zip
62 1
            $zip->close();
63
64
            // Return zip destination
65 1
            return $destZip;
66
        }
67
68
        // Something went wrong
69 1
        throw new Exception(Craft::t('Failed to generate the zipfile'));
70
    }
71
}
72