AbstractTest::createTemporaryFileName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * apparat-dev
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Dev
8
 * @subpackage  Apparat\Dev\Tests
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Apparat\Dev\Tests;
38
39
use Apparat\Dev\Module;
40
41
/**
42
 * Basic tests for generic files
43
 *
44
 * @package     Apparat\Dev
45
 * @subpackage  Apparat\Dev\Tests
46
 */
47
abstract class AbstractTest extends \PHPUnit_Framework_TestCase
48
{
49
    /**
50
     * Temporary files
51
     *
52
     * @var array
53
     */
54
    protected $tmpFiles = [];
55
    /**
56
     * Temporary directories
57
     *
58
     * @var array
59
     */
60
    protected $tmpDirectories = [];
61
62
    /**
63
     * This method is called before the first test of this test class is run.
64
     */
65
    public static function setUpBeforeClass()
66
    {
67
        Module::autorun();
68
    }
69
70
    /**
71
     * Tests if two arrays equal in their keys and values
72
     *
73
     * @param array $expected Expected result
74
     * @param array $actual Actual result
75
     * @param string $message Message
76
     */
77
    public function assertArrayEquals(array $expected, array $actual, $message = '')
78
    {
79
        $this->assertEquals(
80
            $this->sortArrayForComparison($expected),
81
            $this->sortArrayForComparison($actual),
82
            $message
83
        );
84
    }
85
86
    /**
87
     * Recursively sort an array for comparison with another array
88
     *
89
     * @param array $array Array
90
     * @return array                Sorted array
91
     */
92
    protected function sortArrayForComparison(array $array)
93
    {
94
        // Tests if all array keys are numeric
95
        $allNumeric = true;
96
        foreach (array_keys($array) as $key) {
97
            if (!is_numeric($key)) {
98
                $allNumeric = false;
99
                break;
100
            }
101
        }
102
103
        // If not all keys are numeric: Sort the array by key
104
        if (!$allNumeric) {
105
            ksort($array, SORT_STRING);
106
            return $this->sortArrayRecursive($array);
107
        }
108
109
        // Sort them by data type and value
110
        $array = $this->sortArrayRecursive($array);
111
        usort(
112
            $array,
113
            function (
114
                $first,
115
                $second
116
            ) {
117
                $aType = gettype($first);
118
                $bType = gettype($second);
119
                if ($aType === $bType) {
120
                    switch ($aType) {
121
                        case 'array':
122
                            return strcmp(implode('', array_keys($first)), implode('', array_keys($second)));
123
                        case 'object':
124
                            return strcmp(spl_object_hash($first), spl_object_hash($second));
125
                        default:
126
                            return strcmp(strval($first), strval($second));
127
                    }
128
                }
129
130
                return strcmp($aType, $bType);
131
            }
132
        );
133
134
        return $array;
135
    }
136
137
    /**
138
     * Recursively sort an array for comparison
139
     *
140
     * @param array $array Original array
141
     * @return array Sorted array
142
     */
143
    protected function sortArrayRecursive(array $array)
144
    {
145
146
        // Run through all elements and sort them recursively if they are an array
147
        reset($array);
148
        while (list($key, $value) = each($array)) {
149
            if (is_array($value)) {
150
                $array[$key] = $this->sortArrayForComparison($value);
151
            }
152
        }
153
154
        return $array;
155
    }
156
157
    /**
158
     * Tears down the fixture
159
     */
160
    protected function tearDown()
161
    {
162
        foreach ($this->tmpDirectories as $tmpDirectory) {
163
            $this->scanTemporaryDirectory($tmpDirectory);
164
        }
165
        foreach (array_reverse($this->tmpFiles) as $tmpFile) {
166
            @is_file($tmpFile) ? @unlink($tmpFile) : @rmdir($tmpFile);
167
        }
168
    }
169
170
    /**
171
     * Scan a temporary directory and register all files and subdirectories (recursively)
172
     *
173
     * @param string $directory Directory
174
     */
175
    protected function scanTemporaryDirectory($directory)
176
    {
177
        foreach (scandir($directory) as $fileOrDirectory) {
178
            if ($fileOrDirectory !== '.' && $fileOrDirectory !== '..' && !is_link($fileOrDirectory)) {
179
                $fileOrDirectory = $directory.DIRECTORY_SEPARATOR.$fileOrDirectory;
180
                $this->tmpFiles[] = $fileOrDirectory;
181
                if (is_dir($fileOrDirectory)) {
182
                    $this->scanTemporaryDirectory($fileOrDirectory);
183
                }
184
            }
185
        }
186
    }
187
188
    /**
189
     * Prepare and register a temporary file name
190
     *
191
     * @return string Temporary file name
192
     */
193
    protected function createTemporaryFileName()
194
    {
195
        $tempFileName = $this->createTemporaryFile();
196
        unlink($tempFileName);
197
        return $tempFileName;
198
    }
199
200
    /**
201
     * Prepare and register a temporary file
202
     *
203
     * @return string Temporary file name
204
     */
205
    protected function createTemporaryFile()
206
    {
207
        return $this->tmpFiles[] = tempnam(sys_get_temp_dir(), 'apparat_test_');
208
    }
209
210
    /**
211
     * Register a temporary directory that needs to be deleted recursively on shutdown
212
     *
213
     * @param string $directory Directory
214
     * @return string Directory
215
     */
216
    protected function registerTemporaryDirectory($directory)
217
    {
218
        return $this->tmpDirectories[] = $this->tmpFiles[] = $directory;
219
    }
220
221
    /**
222
     * Normalize HTML contents
223
     *
224
     * @param string $html Original HTML
225
     * @return string Normalized HTML
226
     */
227
    protected function normalizeHtml($html)
228
    {
229
        $htmlDom = new \DOMDocument();
230
        $htmlDom->preserveWhiteSpace = false;
231
        $htmlDom->formatOutput = false;
232
        $htmlDom->loadXML("<html><head><title>apparat</title></head><body>$html</body></html>");
233
        return $htmlDom->saveXML();
234
    }
235
}
236