GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 3ff363...d22dd4 )
by Marc
03:50
created

BridgeFileSystem::removeJob()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 12
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @package: chapi
4
 *
5
 * @author:  msiebeneicher
6
 * @since:   2015-07-29
7
 *
8
 */
9
10
namespace Chapi\Service\JobRepository;
11
12
use Chapi\Component\Cache\CacheInterface;
13
use Chapi\Entity\Chronos\ChronosJobEntity;
14
use Chapi\Entity\JobEntityInterface;
15
use Chapi\Entity\Marathon\MarathonAppEntity;
16
use Chapi\Exception\JobLoadException;
17
use Symfony\Component\Filesystem\Filesystem;
18
use Webmozart\Glob\Glob;
19
20
class BridgeFileSystem implements BridgeInterface
21
{
22
    /**
23
     * @var Filesystem
24
     */
25
    private $oFileSystemService;
26
27
    /**
28
     * @var CacheInterface
29
     */
30
    private $oCache;
31
32
    /**
33
     * @var string
34
     */
35
    private $sRepositoryDir = '';
36
37
    /**
38
     * @var string[]
39
     */
40
    private $aDirectorySeparators = ['.', ':', '-', '\\'];
41
42
    /**
43
     * @var array
44
     */
45
    private $aJobFileMap = [];
46
47
    /**
48
     * @var array
49
     */
50
    private $aGroupedApps = [];
51
52
    /**
53
     * @param Filesystem $oFileSystemService
54
     * @param CacheInterface $oCache
55
     * @param string $sRepositoryDir
56
     */
57 9
    public function __construct(
58
        Filesystem $oFileSystemService,
59
        CacheInterface $oCache,
60
        $sRepositoryDir
61
    )
62
    {
63 9
        $this->oFileSystemService = $oFileSystemService;
64 9
        $this->oCache = $oCache;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 13 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
65 9
        $this->sRepositoryDir = $sRepositoryDir;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
66 9
    }
67
68
    /**
69
     * @return JobEntityInterface[]
70
     */
71 8
    public function getJobs()
72
    {
73 8
        if (empty($this->aJobFileMap))
74
        {
75 8
            $_aJobFiles = $this->getJobFilesFromFileSystem($this->sRepositoryDir);
76 8
            return $this->loadJobsFromFileContent($_aJobFiles, true);
77
        }
78 4
        return $this->loadJobsFromFileContent($this->aJobFileMap, false);
79
    }
80
81
    /**
82
     * @param ChronosJobEntity|JobEntityInterface $oJobEntity
83
     * @return bool
84
     * @throws JobLoadException
85
     */
86 2
    public function addJob(JobEntityInterface $oJobEntity)
87
    {
88
        // generate job file path by name
89 2
        $_sJobFile = $this->generateJobFilePath($oJobEntity);
90
91 2
        if ($this->hasDumpFile($_sJobFile, $oJobEntity))
92
        {
93 2
            $this->setJobFileToMap($oJobEntity->getKey(), $_sJobFile);
94 2
            return true;
95
        }
96
97
        return false;
98
    }
99
100
    /**
101
     * @param JobEntityInterface $oJobEntity
102
     * @return bool
103
     */
104 3
    public function updateJob(JobEntityInterface $oJobEntity)
105
    {
106 3
        if (in_array($oJobEntity->getKey(), $this->aGroupedApps))
107
        {
108
            // marathon's group case where app belongs to a group file
109 1
            return $this->dumpFileWithGroup(
110 1
                $this->getJobFileFromMap($oJobEntity->getKey()),
111
                $oJobEntity
112
            );
113
        }
114 2
        return $this->hasDumpFile(
115 2
            $this->getJobFileFromMap($oJobEntity->getKey()),
116
            $oJobEntity
117
        );
118
    }
119
120
    /**
121
     * @param ChronosJobEntity|JobEntityInterface $oJobEntity
122
     * @return bool
123
     */
124 3
    public function removeJob(JobEntityInterface $oJobEntity)
125
    {
126 3
        if (in_array($oJobEntity->getKey(), $this->aGroupedApps))
127
        {
128 1
            $_sJobFile = $this->getJobFileFromMap($oJobEntity->getKey());
129 1
            $this->dumpFileWithGroup(
130
                $_sJobFile,
131
                $oJobEntity,
132 1
                false
133
            );
134
135 1
            unset($this->aJobFileMap[$oJobEntity->getKey()]);
136 1
            return true;
137
        }
138
139 2
        $_sJobFile = $this->getJobFileFromMap($oJobEntity->getKey());
140 2
        $this->oFileSystemService->remove($_sJobFile);
141
142 2
        return $this->hasUnsetJobFileFromMap($oJobEntity->getKey(), $_sJobFile);
143
    }
144
145
    /**
146
     * @param JobEntityInterface $oJobEntity
147
     * @return string
148
     */
149 2
    private function generateJobFilePath(JobEntityInterface $oJobEntity)
150
    {
151 2
        if ($oJobEntity->getEntityType() == JobEntityInterface::CHRONOS_TYPE)
152
        {
153 1
            $_sJobPath = str_replace(
154 1
                $this->aDirectorySeparators,
155 1
                DIRECTORY_SEPARATOR,
156 1
                $oJobEntity->getKey()
157
            );
158
        }
159
        else
160
        {
161 1
            $_sJobPath = $oJobEntity->getKey();
162
        }
163
164 2
        return $this->sRepositoryDir . DIRECTORY_SEPARATOR . $_sJobPath . '.json';
165
    }
166
167
    /**
168
     * @param string $sPath
169
     * @param array $aJobFiles
170
     * @return array
171
     */
172 8
    private function getJobFilesFromFileSystem($sPath, array &$aJobFiles = [])
173
    {
174 8
        if (!is_dir($sPath))
175
        {
176
            throw new \RuntimeException(sprintf('Path "%s" is not valid', $sPath));
177
        }
178
179 8
        $_aTemp = Glob::glob(rtrim($sPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*');
180
181 8
        foreach ($_aTemp as $_sPath)
182
        {
183 7
            if (is_file($_sPath) && preg_match('~\.json~i', $_sPath))
184
            {
185 6
                $aJobFiles[] = $_sPath;
186
            }
187 6
            elseif (is_dir($_sPath))
188
            {
189 7
                $this->getJobFilesFromFileSystem($_sPath, $aJobFiles);
190
            }
191
        }
192
193 8
        return $aJobFiles;
194
    }
195
196
    /**
197
     * @param string $sJobName
198
     * @param string $sJobFile
199
     * @throws JobLoadException
200
     */
201 7
    private function setJobFileToMap($sJobName, $sJobFile)
202
    {
203
        // set path to job file map
204 7
        if (isset($this->aJobFileMap[$sJobName]))
205
        {
206 1
            throw new JobLoadException(
207 1
                sprintf('The jobname "%s" already exists. Jobnames have to be unique - Please check your local jobfiles for duplicate entries.', $sJobName),
208 1
                JobLoadException::ERROR_CODE_DUPLICATE_JOB_ID
209
            );
210
        }
211
212 7
        $this->aJobFileMap[$sJobName] = $sJobFile;
213 7
    }
214
215
    /**
216
     * @param string $sJobName
217
     * @return string
218
     * @throws \RuntimeException
219
     */
220 4
    private function getJobFileFromMap($sJobName)
221
    {
222 4
        if (!isset($this->aJobFileMap[$sJobName]))
223
        {
224
            throw new \RuntimeException(sprintf('Can\'t find file for job "%s"', $sJobName));
225
        }
226 4
        return $this->aJobFileMap[$sJobName];
227
    }
228
229
    /**
230
     * @param string $sJobName
231
     * @param string $sJobFile
232
     * @return bool
233
     * @throws \RuntimeException
234
     */
235 2
    private function hasUnsetJobFileFromMap($sJobName, $sJobFile = '')
236
    {
237 2
        $_sJobFile = (!empty($sJobFile)) ? $sJobFile : $this->getJobFileFromMap($sJobName);
238 2
        if (file_exists($_sJobFile))
239
        {
240
            throw new \RuntimeException(sprintf('Job file "%s" for job "%s" still exists.', $_sJobFile, $sJobName));
241
        }
242
243
        // unset path from job file map
244 2
        unset($this->aJobFileMap[$sJobName]);
245 2
        return true;
246
    }
247
248
    /**
249
     * @param array $aJobFiles
250
     * @param bool $bSetToFileMap
251
     * @return JobEntityInterface[]
252
     * @throws JobLoadException
253
     */
254 8
    private function loadJobsFromFileContent(array $aJobFiles, $bSetToFileMap)
255
    {
256 8
        $_aJobs = [];
257
258 8
        foreach ($aJobFiles as $_sJobFilePath)
259
        {
260 8
            $_aJobEntities = [];
261
            // remove comment blocks
262 8
            $_aTemp = json_decode(
263
                preg_replace(
264 8
                    '~\/\*(.*?)\*\/~mis',
265 8
                    '',
266
                    file_get_contents($_sJobFilePath)
267
                )
268
            );
269
270 8
            if ($_aTemp)
271
            {
272
                // chronos
273 7
                if (property_exists($_aTemp, 'name'))
274
                {
275 4
                    $_aJobEntities[] = new ChronosJobEntity($_aTemp);
276
277
                }
278
                //marathon
279 4
                else if (property_exists($_aTemp, 'id'))
280
                {
281 4
                    foreach ($this->getMarathonEntitiesForConfig($_aTemp) as $_oApp)
282
                    {
283 4
                        $_aJobEntities[] = $_oApp;
284
                    }
285
                }
286
                else
287
                {
288
                    throw new JobLoadException(
289
                        'Could not distinguish job as either chronos or marathon',
290
                        JobLoadException::ERROR_CODE_UNKNOWN_ENTITY_TYPE
291
                    );
292
                }
293
294
                /** @var JobEntityInterface $_oJobEntity */
295 7
                foreach ($_aJobEntities as $_oJobEntity)
296
                {
297 7
                    if ($bSetToFileMap)
298
                    {
299
                        // set path to job file map
300 5
                        $this->setJobFileToMap($_oJobEntity->getKey(), $_sJobFilePath);
301
                    }
302
303 7
                    $_aJobs[] = $_oJobEntity;
304
                }
305
306
            }
307
            else
308
            {
309 1
                throw new JobLoadException(
310 1
                    sprintf('Unable to load json job data from "%s". Please check if the json is valid.', $_sJobFilePath),
311 8
                    JobLoadException::ERROR_CODE_NO_VALID_JSON
312
                );
313
            }
314
        }
315
316 6
        return $_aJobs;
317
    }
318
319
320 4
    private function getMarathonEntitiesForConfig($aEntityData)
321
    {
322 4
        $_aRet = [];
323 4
        if (property_exists($aEntityData, 'apps'))
324
        {
325
            // store individual apps like single apps
326 2
            foreach ($aEntityData->apps as $_oApp)
327
            {
328 2
                $_oGroupEntity = new MarathonAppEntity($_oApp);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
329 2
                $this->aGroupedApps[] = $_oApp->id;
330 2
                $_aRet[] = $_oGroupEntity;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 14 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
331
            }
332
        }
333
        else
334
        {
335 2
            $_aRet[] = new MarathonAppEntity($aEntityData);
336
        }
337 4
        return $_aRet;
338
    }
339
340
    /**
341
     * @param string $sJobFile
342
     * @param JobEntityInterface $oJobEntity
343
     * @return bool
344
     */
345 2
    private function hasDumpFile($sJobFile, JobEntityInterface $oJobEntity)
346
    {
347 2
        $this->oFileSystemService->dumpFile(
348
            $sJobFile,
349 2
            json_encode($oJobEntity, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
350
        );
351
352 2
        return (file_exists($sJobFile));
353
    }
354
355
    /**
356
     * @param string $sJobFile
357
     * @param JobEntityInterface $oJobEntity
358
     * @param bool $bAdd
359
     * @return bool
360
     */
361 2
    private function dumpFileWithGroup($sJobFile, JobEntityInterface $oJobEntity, $bAdd = true)
0 ignored issues
show
Coding Style introduced by
function dumpFileWithGroup() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
362
    {
363 2
        $_sGroupConfig = file_get_contents($sJobFile);
364
365 2
        $_oDecodedConfig = json_decode(preg_replace(
366 2
            '~\/\*(.*?)\*\/~mis',
367 2
            '',
368
            $_sGroupConfig
369
        ));
370
371 2
        if (!property_exists($_oDecodedConfig, 'apps'))
372
        {
373
            throw new \RuntimeException(sprintf(
374
                'Job file %s does not contain group configuration. But, "%s" belongs to group %s',
375
                $sJobFile,
376
                $oJobEntity->getKey(),
377
                $_oDecodedConfig->id
378
            ));
379
        }
380
381 2
        $_bAppFound = false;
382 2
        foreach ($_oDecodedConfig->apps as $key => $_oApp)
383
        {
384 2
            if ($_oApp->id == $oJobEntity->getKey())
385
            {
386 2
                if (!$bAdd)
387
                {
388 1
                    array_splice($_oDecodedConfig->apps, $key, 1);
389 1
                    if (count($_oDecodedConfig->apps) == 0)
390
                    {
391
                        $this->oFileSystemService->remove($sJobFile);
392
                        $iIndex = array_search($oJobEntity->getKey(), $this->aGroupedApps);
393
                        if ($iIndex)
394
                        {
395
                            unset($this->aGroupedApps[$iIndex]);
396
                        }
397 1
                        return false;
398
                    }
399
                } else {
400 1
                    $_oDecodedConfig->apps[$key] = $oJobEntity;
401
                }
402 2
                $_bAppFound = true;
403
            }
404
        }
405
406 2
        if (!$_bAppFound)
407
        {
408
            throw new \RuntimeException(sprintf(
409
                'Could update job. job %s could not be found in the group file %s.',
410
                $oJobEntity->getKey(),
411
                $sJobFile
412
            ));
413
        }
414
415 2
        $_sUpdatedConfig = json_encode($_oDecodedConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
416
417 2
        $this->oFileSystemService->dumpFile(
418
            $sJobFile,
419
            $_sUpdatedConfig
420
        );
421
422 2
        return (file_exists($sJobFile));
423
    }
424
}