Passed
Push — develop ( 3b1736...62d6da )
by Paul
03:12
created

ConfigManager::setTimestamp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
namespace GeminiLabs\Pollux\Config;
4
5
use GeminiLabs\Pollux\Application;
6
use GeminiLabs\Pollux\Config\Config;
7
use GeminiLabs\Pollux\MetaBox\SiteMetaManager;
8
use Symfony\Component\Yaml\Exception\DumpException;
9
use Symfony\Component\Yaml\Exception\ParseException;
10
use Symfony\Component\Yaml\Yaml;
11
12
/**
13
 * @property $updated
14
 */
15
class ConfigManager extends SiteMetaManager
16
{
17
	const RAW_STRINGS = [
18
		'__', '_n', '_x', 'sprintf',
19
	];
20
21
	public function __construct()
22
	{
23
		$this->app = Application::getInstance();
0 ignored issues
show
Bug introduced by
The property app does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
24
		$this->options = $this->buildConfig();
25
	}
26
27
	/**
28
	 * @param string $group
29
	 * @return object|array|null
30
	 */
31
	public function __get( $group )
32
	{
33
		if( $group == 'yaml' ) {
34
			return $this->yaml();
35
		}
36
		return parent::__get( $group );
37
	}
38
39
	/**
40
	 * @return array
41
	 */
42
	public function buildConfig()
43
	{
44
		$yamlFile = $this->getYamlFile();
45
		$yaml = $this->normalize(
46
			$this->parseYaml( file_get_contents( $yamlFile ))
47
		);
48
		if( !$yaml['disable_config'] ) {
49
			$config = $this->normalizeArray(
50
				array_filter( (array) get_option( Config::id(), [] ))
51
			);
52
		}
53
		return empty( $config )
54
			? $this->setTimestamp( $yaml, filemtime( $yamlFile ))
0 ignored issues
show
Documentation introduced by
filemtime($yamlFile) is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
55
			: $this->normalize( $config );
56
	}
57
58
	/**
59
	 * @return object
60
	 */
61
	public function compile()
62
	{
63
		$configFile = $this->getCompileDestination();
64
		if( $this->shouldCompile( $configFile )) {
65
			file_put_contents( $configFile, sprintf( '<?php // DO NOT MODIFY THIS FILE DIRECTLY!%sreturn (object) %s;',
66
				PHP_EOL,
67
				$this->parseRawStrings( var_export( $this->setTimestamp( $this->options ), true ))
68
			));
69
		}
70
		return include $configFile;
71
	}
72
73
	/**
74
	 * @return string
75
	 */
76
	public function convertArrayToYaml( array $array )
77
	{
78
		return !empty( $array )
79
			? trim( $this->parseRawStrings( $this->dumpYaml( $array )))
80
			: '';
81
	}
82
83
	/**
84
	 * @return string
85
	 */
86
	public function getCompileDestination( $filename = 'pollux-config.php' )
87
	{
88
		$filename = apply_filters( 'pollux/config/dist/file', $filename );
89
		$storagePath = apply_filters( 'pollux/config/dist/location', WP_CONTENT_DIR );
90
		wp_mkdir_p( $storagePath );
91
		return sprintf( '%s%s', trailingslashit( $storagePath ), $filename );
92
	}
93
94
	/**
95
	 * @return string
96
	 */
97
	public function getYamlFile()
98
	{
99
		$theme = wp_get_theme();
100
		$configYaml = apply_filters( 'pollux/config/src/file', 'pollux.yml' );
101
		$configLocations = apply_filters( 'pollux/config/src/location', [
102
			trailingslashit( trailingslashit( $theme->theme_root ) . $theme->stylesheet ),
103
			trailingslashit( trailingslashit( $theme->theme_root ) . $theme->template ),
104
			trailingslashit( WP_CONTENT_DIR ),
105
			trailingslashit( ABSPATH ),
106
			trailingslashit( dirname( ABSPATH )),
107
			trailingslashit( dirname( dirname( ABSPATH ))),
108
		]);
109
		foreach( (array) $configLocations as $location ) {
110
			if( !file_exists( $location . $configYaml ))continue;
111
			return $location . $configYaml;
112
		}
113
		return $this->app->path( 'defaults.yml' );
114
	}
115
116
	/**
117
	 * @return array
118
	 */
119
	public function normalizeArray( array $array )
120
	{
121
		return array_map( function( $value ) {
122
			return !is_numeric( $value ) && is_string( $value )
123
				? $this->parseYaml( $value )
124
				: $value;
125
		}, $array );
126
	}
127
128
	/**
129
	 * @return array
130
	 */
131
	public function normalizeYamlValues( array $array )
132
	{
133
		return array_map( function( $value ) {
134
			return is_array( $value )
135
				? $this->convertArrayToYaml( $value )
136
				: $value;
137
		}, $array );
138
	}
139
140
	/**
141
	 * @return array
142
	 */
143
	public function setTimestamp( array $config, $timestamp = false )
144
	{
145
		$timestamp || $timestamp = time();
146
		$config['updated'] = $timestamp;
147
		return $config;
148
	}
149
150
	/**
151
	 * @return object
152
	 */
153
	public function yaml()
154
	{
155
		return (object) $this->normalizeYamlValues( $this->options );
156
	}
157
158
	/**
159
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
160
	 */
161
	protected function dumpYaml( array $array )
162
	{
163
		try {
164
			return Yaml::dump( $array, 13, 2 );
165
		}
166
		catch( DumpException $e ) {
167
			error_log( print_r( $e->getMessage(), 1 ));
168
		}
169
	}
170
171
	/**
172
	 * @return array
173
	 */
174
	protected function normalize( array $config )
175
	{
176
		return wp_parse_args(
177
			$config,
178
			$this->parseYaml( file_get_contents( $this->app->path( 'defaults.yml' )))
179
		);
180
	}
181
182
	/**
183
	 * @param string $configString
184
	 * @return string
185
	 */
186
	protected function parseRawStrings( $configString )
187
	{
188
		$strings = apply_filters( 'pollux/config/raw_strings', static::RAW_STRINGS );
189
		$pattern = '/(\')((' . implode( '|', $strings ) . ')\(?.+\))(\')/';
190
		return stripslashes(
191
			preg_replace_callback( $pattern, function( $matches ) {
192
				return str_replace( "''", "'", $matches[2] );
193
			}, $configString )
194
		);
195
	}
196
197
	/**
198
	 * @return mixed
199
	 */
200
	protected function parseYaml( $value )
201
	{
202
		try {
203
			return Yaml::parse( $value );
204
		}
205
		catch( ParseException $e ) {
206
			// http://api.symfony.com/3.2/Symfony/Component/Yaml/Exception/ParseException.html
207
			error_log( print_r( sprintf("Unable to parse the YAML string: %s", $e->getMessage()), 1 ));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Unable to parse the YAML string: %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
208
			error_log( print_r( $e->getParsedFile(), 1 ));
209
			error_log( print_r( $e->getParsedLine(), 1 ));
210
			error_log( print_r( $e->getSnippet(), 1 ));
211
		}
212
	}
213
214
	/**
215
	 * @param string $configFile
216
	 * @return bool
217
	 */
218
	protected function shouldCompile( $configFile )
219
	{
220
		if( !file_exists( $configFile )) {
221
			return true;
222
		}
223
		$config = include $configFile;
224
		if( $this->updated >= $config->updated ) {
0 ignored issues
show
Documentation introduced by
The property updated does not exist on object<GeminiLabs\Pollux\Config\ConfigManager>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
225
			return true;
226
		}
227
		return filemtime( $this->getYamlFile() ) >= $config->updated;
228
	}
229
}
230