Completed
Push — master ( fda08e...d5e2fd )
by Sebastien
02:30
created

HackedProjectWebFilesDownloader::extractArchive()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 24
rs 8.9714
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
3
namespace Cerbere\Model\Hacked;
4
5
use splitbrain\PHPArchive\Archive;
6
use splitbrain\PHPArchive\Tar;
7
8
/**
9
 * Downloads a project using a standard Drupal method.
10
 */
11
class HackedProjectWebFilesDownloader extends HackedProjectWebDownloader
12
{
13
    /**
14
     * @return string|false
15
     */
16
    public function getDownloadLink()
17
    {
18
        $version = $this->project->getVersion();
19
20
        // Remove 'dev' tailing flag from version name.
21
        if (preg_match('/(\+\d+\-dev)$/', $version)) {
22
            $version = preg_replace('/(\+\d+\-dev)$/', '', $version);
23
        }
24
25
        if ($release = $this->project->getRelease($version)) {
26
            return $release->getDownloadLink();
27
        }
28
29
        return false;
30
    }
31
32
    /**
33
     * @return bool|string
34
     */
35
    public function downloadFile()
36
    {
37
        $destination = $this->getDestination();
38
39
        if (!($release_url = $this->getDownloadLink())) {
40
            return false;
41
        }
42
43
        // If our directory already exists, we can just return the path to this cached version
44
        $whiteList = array('.', '..', 'CVS', '.svn', '.git');
45
        if (file_exists($destination) && count(HackedFileGroup::scanDirectory($destination, '/.*/', $whiteList))
46
        ) {
47
            return $destination;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $destination; (string) is incompatible with the return type of the parent method Cerbere\Model\Hacked\Hac...ownloader::downloadFile of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
48
        }
49
50
        // Build the destination folder tree if it doesn't already exists.
51
        @mkdir($destination, 0775, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
52
53
        if (!($local_file = $this->getFile($release_url))) {
54
            return false;
55
        }
56
57
        try {
58
            $this->extractArchive($local_file, $destination);
59
        } catch (\Exception $e) {
60
            echo $e->getMessage() . "\n";
61
62
            return false;
63
        }
64
65
        return true;
66
    }
67
68
    /**
69
     * Copies a file from $url to the temporary directory for updates.
70
     *
71
     * If the file has already been downloaded, returns the the local path.
72
     *
73
     * @param $url
74
     *   The URL of the file on the server.
75
     *
76
     * @return string
77
     *   Path to local file.
78
     */
79
    protected function getFile($url)
80
    {
81
        $parsed_url = parse_url($url);
82
        $remote_schemes = array('http', 'https', 'ftp', 'ftps', 'smb', 'nfs');
83
84
        if (!in_array($parsed_url['scheme'], $remote_schemes)) {
85
            // This is a local file, just return the path.
86
            return realpath($url);
87
        }
88
89
        // Todo: use Symfony's cache objects
90
        // Check the cache and download the file if needed.
91
        $cache_directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'hacked-cache';
92
        $local = $cache_directory . DIRECTORY_SEPARATOR . basename($parsed_url['path']);
93
94
        if (!file_exists($cache_directory)) {
95
            @mkdir($cache_directory, 0775, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
96
        }
97
98
        // Todo: use guzzle.
99
        $content = file_get_contents($url);
100
101
        if ($content !== false && file_put_contents($local, $content)) {
102
            return $local;
103
        }
104
105
        return false;
106
    }
107
108
    /**
109
     * Unpack a downloaded archive file.
110
     *
111
     * @param string $file
112
     *   The filename of the archive you wish to extract.
113
     * @param string $directory
114
     *   The directory you wish to extract the archive into.
115
     * @return Archive
116
     *   The Archiver object used to extract the archive.
117
     * @throws \Exception on failure.
118
     */
119
    protected function extractArchive($file, $directory)
120
    {
121
        $archive = new Tar();
122
123
        // Remove the directory if it exists, otherwise it might contain a mixture of
124
        // old files mixed with the new files (e.g. in cases where files were removed
125
        // from a later release).
126
        $archive->open($file);
127
        $files = $archive->contents();
128
129
        // First entry contains the root folder.
130
        $project_path = $files[0]->getPath();
131
132
        if (file_exists($directory)) {
133
            $this->removeDir($directory);
134
        }
135
136
        // Reopen archive to extract all files.
137
        $archive->open($file);
138
        // Strip first folder level.
139
        $archive->extract($directory, $project_path);
140
141
        return $archive;
142
    }
143
}
144