PhpFile::write()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php /** @noinspection PhpIncludeInspection */
2
3
/**
4
 * This software package is licensed under `AGPL-3.0-only, proprietary` license[s].
5
 *
6
 * @package   maslosoft/signals
7
 * @license   AGPL-3.0-only, proprietary
8
 *
9
 * @copyright Copyright (c) Peter Maselkowski <[email protected]>
10
 * @link      https://maslosoft.com/signals/
11
 */
12
13
namespace Maslosoft\Signals\Builder\IO;
14
15
use Maslosoft\Cli\Shared\Helpers\PhpExporter;
16
use Maslosoft\Signals\Interfaces\BuilderIOInterface;
17
use Maslosoft\Signals\Signal;
18
19
/**
20
 * PhpFileOutput
21
 * @codeCoverageIgnore
22
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
23
 */
24
class PhpFile implements BuilderIOInterface
25
{
26
27
	/**
28
	 * Generated path is directory, where signals definition will be stored.
29
	 * Path is relative to project root.
30
	 *
31
	 * **This directory must be writable by command line user**
32
	 *
33
	 * **This directory should be committed and distributed along with the project code**
34
	 *
35
	 * @var string
36
	 */
37
	public $generatedPath = 'generated';
38
39
	/**
40
	 * File name for file containing signals definitions, in most cases
41
	 * leaving default value is fine.
42
	 *
43
	 * @var string
44
	 */
45
	public $configFilename = 'signals-definition.php';
46
47
	/**
48
	 * Signal instance
49
	 * @var Signal
50
	 */
51
	private $signal = null;
52
53
	public function read(): array
54
	{
55
		$file = $this->generatedPath . '/' . $this->configFilename;
56
		if (file_exists($file))
57
		{
58
			return (array)require $file;
59
		}
60
		else
61
		{
62
			$this->signal->getLogger()->debug('Config file "{file}" does not exists, have you generated signals config file?', ['file' => $file]);
63
		}
64
		return [];
65
	}
66
67
	public function setSignal(Signal $signal)
68
	{
69
		$this->signal = $signal;
70
		return $this;
71
	}
72
73
	public function write($data): bool
74
	{
75
		$path = sprintf("%s/%s", $this->generatedPath, $this->configFilename);
76
77
		// Use dirname here in case configFilename contains dir
78
		$dir = dirname($path);
79
		if (!is_dir($dir))
80
		{
81
			mkdir($dir, 0777, true);
82
		}
83
		return file_put_contents($path, PhpExporter::export($data, 'Auto generated, any changes will be lost'));
84
	}
85
86
}
87