Completed
Push — master ( 64470f...3a69fd )
by Florian
02:24
created

Finder::getContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Laposte\DatanovaBundle\Service;
4
5
use Psr\Log\LoggerInterface;
6
use Symfony\Component\Config\FileLocator;
7
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
8
use Symfony\Component\Filesystem\Filesystem;
9
10
class Finder
11
{
12
    const DEFAULT_FORMAT = 'JSON';
13
    const RESSOURCES_FOLDER = '@LaposteDatanovaBundle/Resources/dataset';
14
15
    /** @var Filesystem $filesystem */
16
    private $filesystem;
17
18
    /** @var FileLocator $locator */
19
    private $locator;
20
21
    /** @var string $directory */
22
    private $directory;
23
24
    /** @var LoggerInterface $logger */
25
    private $logger;
26
27
    /**
28
     * @param Filesystem $filesystem
29
     * @param FileLocator $locator
30
     * @param string $rootDir
31
     */
32
    public function __construct(Filesystem $filesystem, FileLocator $locator, $rootDir = self::RESSOURCES_FOLDER)
33
    {
34
        $this->filesystem = $filesystem;
35
        $this->locator = $locator;
36
        $rootDir = $this->locator->locate($rootDir);
37
        $this->setWorkingDirectory($rootDir);
0 ignored issues
show
Bug introduced by
It seems like $rootDir defined by $this->locator->locate($rootDir) on line 36 can also be of type array; however, Laposte\DatanovaBundle\S...::setWorkingDirectory() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
38
    }
39
40
    /**
41
     * @param LoggerInterface $logger
42
     */
43
    public function setLogger(LoggerInterface $logger)
44
    {
45
        $this->logger = $logger;
46
    }
47
48
    /**
49
     * @param string $directory the working directory for filesystem operations
50
     */
51
    public function setWorkingDirectory($directory)
52
    {
53
        $directory = preg_replace('#/+#', '/', $directory); // remove multiple slashes
54
        try {
55
            $directory = $this->locator->locate($directory);
56
        } catch (\Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
57
        }
58
        $exists = $this->filesystem->exists($directory);
59
        if (!$exists) {
60
            try {
61
                $this->filesystem->mkdir($directory);
62
                $this->logger->notice("Working directory created at " . $directory);
63
            } catch (IOExceptionInterface $exception) {
64
                $this->logger->error(
65
                    "An error occurred while creating your directory at " . $exception->getPath(),
66
                    $exception->getTrace()
67
                );
68
            }
69
        }
70
        $this->directory = $directory;
0 ignored issues
show
Documentation Bug introduced by
It seems like $directory can also be of type array. However, the property $directory is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
71
    }
72
73
    /**
74
     * Check if a dataset local file exists
75
     *
76
     * @param string $dataset
77
     * @param string $format
78
     * @param string $filter
79
     *
80
     * @return bool
81
     */
82
    public function exists($dataset, $format, $filter = null)
83
    {
84
        $uri = $this->getFilePath($dataset, $format, $filter);
85
86
        return $this->filesystem->exists($uri);
87
    }
88
89
    /**
90
     * @param string $dataset
91
     * @param string $format
92
     * @param string $filter
93
     *
94
     * @return string
95
     */
96
    private function getFilePath($dataset, $format, $filter = null)
97
    {
98
        $filter = preg_replace('#:|=#', '_', $filter);
99
        $filepath = sprintf(
100
            '%s%s%s%s%s_%s.%s',
101
            $this->directory,
102
            DIRECTORY_SEPARATOR,
103
            $dataset,
104
            DIRECTORY_SEPARATOR,
105
            $dataset,
106
            $filter,
107
            $format
108
        );
109
        $filepath = preg_replace('#/+#', '/', $filepath); // remove multiple slashes
110
111
        return $filepath;
112
    }
113
114
    /**
115
     * Save a records to dataset file
116
     *
117
     * @param string $dataset
118
     * @param string $content
119
     * @param string $format
120
     * @param string $filter
121
     * @param bool $force
122
     *
123
     * @return false|string saved file path
124
     */
125
    public function save($dataset, $content, $format = self::DEFAULT_FORMAT, $filter = null, $force = false)
126
    {
127
        $saved = false;
128
        $filename = $dataset;
129
        $path = $this->getFilePath($filename, $format, $filter);
130
        if ($this->filesystem->exists($path) && !$force) {
131
            $this->logger->error("An error occurred while saving existing dataset at " . $path);
132
        } else {
133
            try {
134
                $this->filesystem->dumpFile($path, $content);
135
                $this->logger->notice(sprintf('Saving %s dataset at %s', $dataset, $path));
136
                $saved = realpath($path);
137
            } catch (IOExceptionInterface $exception) {
138
                $this->logger->error(
139
                    "An error occurred while saving the dataset at " . $exception->getPath(),
140
                    $exception->getTrace()
141
                );
142
            }
143
        }
144
145
        return $saved;
146
    }
147
148
    /**
149
     * @param string $dataset
150
     * @param string $format
151
     * @param string $filter
152
     *
153
     * @return false|string dataset file path
154
     */
155
    public function findDataset($dataset, $format = self::DEFAULT_FORMAT, $filter = null)
156
    {
157
        $datasetPath = false;
158
        $path = $this->getFilePath($dataset, $format, $filter);
159
        if ($this->filesystem->exists($path)) {
160
            $datasetPath = realpath($path);
161
        }
162
163
        return $datasetPath;
164
    }
165
166
    /**
167
     * @param string $filepath
168
     *
169
     * @return null|string
170
     */
171
    public function getContent($filepath)
172
    {
173
        $content = null;
174
        if (file_exists($filepath)) {
175
            $content = file_get_contents($filepath);
176
        }
177
178
        return $content;
179
    }
180
}
181