Completed
Push — master ( 8f08b6...666f26 )
by Florian
02:50
created

Finder::setWorkingDirectory()   B

Complexity

Conditions 5
Paths 24

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 29
ccs 0
cts 23
cp 0
rs 8.439
cc 5
eloc 20
nc 24
nop 1
crap 30
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\IOException;
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, null, true);
37
        if (false === is_string($rootDir)) {
38
            throw new \InvalidArgumentException('Unexpected root dir type');
39
        }
40
        $this->setWorkingDirectory($rootDir);
41
    }
42
43
    /**
44
     * @param LoggerInterface $logger
45
     */
46
    public function setLogger(LoggerInterface $logger)
47
    {
48
        $this->logger = $logger;
49
    }
50
51
    /**
52
     * @param string $path the working directory for filesystem operations
53
     *
54
     * @throws \InvalidArgumentException
55
     * @throws IOException
56
     */
57
    public function setWorkingDirectory($path)
58
    {
59
        $directory = preg_replace('#/+#', '/', $path); // remove multiple slashes
60
        try {
61
            $directory = $this->locator->locate($directory);
62
            if (false === is_string($directory)) {
63
                $directory = strval(reset($directory));
64
                $this->logger->alert(
65
                    sprintf('Ambiguous filename %s, choosing %s', $path, $directory)
66
                );
67
            }
68
        } catch (\InvalidArgumentException $exception) {
69
            // continue to check if dir exists even if locator doesn't locate
70
        }
71
        $exists = $this->filesystem->exists($directory);
72
        if (!$exists) {
73
            try {
74
                $this->filesystem->mkdir($directory);
75
                $this->logger->notice("Working directory created at " . $directory);
76
            } catch (IOException $exception) {
77
                $this->logger->error(
78
                    "An error occurred while creating directory at " . $exception->getPath(),
79
                    $exception->getTrace()
80
                );
81
                throw $exception;
82
            }
83
        }
84
        $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...
85
    }
86
87
    /**
88
     * Check if a dataset local file exists
89
     *
90
     * @param string $dataset
91
     * @param string $format
92
     * @param string $filter
93
     *
94
     * @return bool
95
     */
96
    public function exists($dataset, $format, $filter = null)
97
    {
98
        $uri = $this->getFilePath($dataset, $format, $filter);
99
100
        return $this->filesystem->exists($uri);
101
    }
102
103
    /**
104
     * @param string $dataset
105
     * @param string $format
106
     * @param string $filter
107
     *
108
     * @return string
109
     */
110
    private function getFilePath($dataset, $format, $filter = null)
111
    {
112
        $filter = preg_replace('#:|=#', '_', $filter);
113
        $filepath = sprintf(
114
            '%s%s%s%s%s_%s.%s',
115
            $this->directory,
116
            DIRECTORY_SEPARATOR,
117
            $dataset,
118
            DIRECTORY_SEPARATOR,
119
            $dataset,
120
            $filter,
121
            $format
122
        );
123
        $filepath = preg_replace('#/+#', '/', $filepath); // remove multiple slashes
124
125
        return $filepath;
126
    }
127
128
    /**
129
     * Save a records to dataset file
130
     *
131
     * @param string $dataset
132
     * @param string $content
133
     * @param string $format
134
     * @param string $filter
135
     * @param bool $force
136
     *
137
     * @return false|string saved file path
138
     */
139
    public function save($dataset, $content, $format = self::DEFAULT_FORMAT, $filter = null, $force = false)
140
    {
141
        $saved = false;
142
        $filename = $dataset;
143
        $path = $this->getFilePath($filename, $format, $filter);
144
        if ($this->filesystem->exists($path) && !$force) {
145
            $this->logger->error("An error occurred while saving existing dataset at " . $path);
146
        } else {
147
            try {
148
                $this->filesystem->dumpFile($path, $content);
149
                $this->logger->notice(sprintf('Saving %s dataset at %s', $dataset, $path));
150
                $saved = realpath($path);
151
            } catch (IOException $exception) {
152
                $this->logger->error(
153
                    "An error occurred while saving the dataset at " . $exception->getPath(),
154
                    $exception->getTrace()
155
                );
156
            }
157
        }
158
159
        return $saved;
160
    }
161
162
    /**
163
     * @param string $dataset
164
     * @param string $format
165
     * @param string $filter
166
     *
167
     * @return false|string dataset file path
168
     */
169
    public function findDataset($dataset, $format = self::DEFAULT_FORMAT, $filter = null)
170
    {
171
        $datasetPath = false;
172
        $path = $this->getFilePath($dataset, $format, $filter);
173
        if ($this->filesystem->exists($path)) {
174
            $datasetPath = realpath($path);
175
        }
176
177
        return $datasetPath;
178
    }
179
180
    /**
181
     * @param string $filepath
182
     *
183
     * @return null|string
184
     */
185
    public function getContent($filepath)
186
    {
187
        $content = null;
188
        if (file_exists($filepath)) {
189
            $content = file_get_contents($filepath);
190
        }
191
192
        return $content;
193
    }
194
}
195