CompileConfigHandler   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 150
rs 10
c 0
b 0
f 0
wmc 23
lcom 1
cbo 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
B execute() 0 44 6
C formatFile() 0 74 17
1
<?php
2
3
// +---------------------------------------------------------------------------+
4
// | This file is part of the Agavi package.                                   |
5
// | Copyright (c) 2005-2011 the Agavi Project.                                |
6
// | Based on the Mojavi3 MVC Framework, Copyright (c) 2003-2005 Sean Kerr.    |
7
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
17
namespace Agavi\Config;
18
19
use Agavi\Config\Util\Dom\XmlConfigDomElement;
20
use Agavi\Util\Toolkit;
21
use Agavi\Config\Util\Dom\XmlConfigDomDocument;
22
use Agavi\Exception\ParseException;
23
24
/**
25
 * CompileConfigHandler gathers multiple files and puts them into a single
26
 * file. Upon creation of the new file, all comments and blank lines are removed.
27
 *
28
 * @package    agavi
29
 * @subpackage config
30
 *
31
 * @author     Sean Kerr <[email protected]>
32
 * @author     Dominik del Bondio <[email protected]>
33
 * @copyright  Authors
34
 * @copyright  The Agavi Project
35
 *
36
 * @since      0.9.0
37
 *
38
 * @version    $Id$
39
 */
40
class CompileConfigHandler extends XmlConfigHandler
41
{
42
    const XML_NAMESPACE = 'http://agavi.org/agavi/config/parts/compile/1.1';
43
    
44
    /**
45
     * Execute this configuration handler.
46
     *
47
     * @param      XmlConfigDomDocument $document The document to parse.
48
     *
49
     * @return     string Data to be written to a cache file.
50
     *
51
     * @throws     <b>AgaviParseException</b> If a requested configuration file is
52
     *                                        improperly formatted.
53
     *
54
     * @author     Sean Kerr <[email protected]>
55
     * @author     Dominik del Bondio <[email protected]>
56
     * @author     David Zülke <[email protected]>
57
     * @since      0.9.0
58
     */
59
    public function execute(XmlConfigDomDocument $document)
60
    {
61
        // set up our default namespace
62
        $document->setDefaultNamespace(self::XML_NAMESPACE, 'compile');
63
        
64
        $config = $document->documentURI;
65
        
66
        $data = array();
67
        
68
        // let's do our fancy work
69
        foreach ($document->getConfigurationElements() as $configuration) {
70
            if (!$configuration->has('compiles')) {
71
                continue;
72
            }
73
74
            /** @var XmlConfigDomElement $compileFile */
75
            foreach ($configuration->get('compiles') as $compileFile) {
76
                $file = trim($compileFile->getValue());
77
                
78
                $file = Toolkit::expandDirectives($file);
79
                $file = self::replacePath($file);
80
81
                if (!is_readable($file)) {
82
                    // file doesn't exist
83
                    $error = 'Configuration file "%s" specifies nonexistent ' . 'or unreadable file "%s"';
84
                    $error = sprintf($error, $config, $compileFile->getValue());
85
                    throw new ParseException($error);
86
                }
87
                
88
                if (Config::get('core.debug', false)) {
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
89
                    // debug mode, just require() the files, makes for nicer stack traces
90
                    $contents = 'require(' . var_export($file, true) . ');';
91
                } else {
92
                    // no debug mode, so make things fast
93
                    $contents = $this->formatFile(file_get_contents($file));
94
                }
95
                
96
                // append file data
97
                $data[$file] = $contents;
98
            }
99
        }
100
        
101
        return $this->generate($data, $config);
102
    }
103
104
    /**
105
     * Given some data, remove unnecessary formatting and return the new data
106
     *
107
     * @param      string $data Data to format for a compiled file, probably PHP code
108
     *
109
     * @return     string Data with unnecessary content removed
110
     *
111
     * @author     Blake Matheny <[email protected]>
112
     * @author     David Zülke <[email protected]>
113
     * @since      0.11.0
114
     */
115
    protected function formatFile($data)
116
    {
117
        // replace windows and mac format with unix format
118
        $data = str_replace("\r\n", "\n", $data);
119
        $data = str_replace("\r", "\n", $data);
120
121
        // remove comments and tags with tokenizer
122
123
        // I disabled this, it seems broken somehow. doesn't remove all <?php tags. - david
124
125
        if (function_exists('token_get_all')) {
126
            $tokens = token_get_all($data);
127
            $tokenized = null;
128
            // has something been written to tokenized? If so, we can optionally append whitespace.
129
            $appended = false;
130
131
            foreach ($tokens as $token) {
132
                if (is_string($token)) {
133
                    $tokenized .= $token;
134
                    $appended = true;
135
                } else {
136
                    @list($id,$text) = $token;
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
137
                    switch ($id) {
138
                        case T_COMMENT:
139
                        case T_DOC_COMMENT:
140
                        case T_OPEN_TAG:
141
                            $appended = false;
142
                            break;
143
                        case T_CLOSE_TAG:
144
                            $appended = false;
145
                            break;
146
147
                        case T_WHITESPACE:
148
                            // something was appended, optionally add a newline
149
                            if ($appended) {
150
                                $replace = null;
151
                                if (strstr($text, "\n") !== false) {
152
                                    $replace = "\n";
153
                                }
154
                                if ($replace) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replace of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
155
                                    $text = preg_replace('/\s+/m', $replace, $text);
156
                                }
157
                                $tokenized .= $text;
158
                            }
159
                            $appended = false;
160
                            break;
161
                        case T_INLINE_HTML:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
162
                            // If empty T_INLINE_HTML move on
163
                            if (!preg_match('/[^\s]+/m', $text)) {
164
                                $appended = false;
165
                                break;
166
                            }
167
                        default:
168
                            $tokenized .= $text;
169
                            $appended = true;
170
                            break;
171
                    }
172
                }
173
            }
174
            $data = $tokenized;
175
        }
176
        $data = trim($data);
177
        if (substr($data, 0, 5) == '<?php') {
178
            $data = substr($data, 5);
179
        } elseif (substr($data, 0, 2) == '<?') {
180
            $data = substr($data, 2);
181
        }
182
        if (substr($data, -2, 2) == '?>') {
183
            $data = substr($data, 0, -2);
184
        }
185
        $data = preg_replace('/\s*\?>\s*<\?(php)?\s*/', '', $data);
186
187
        return $data;
188
    }
189
}
190