Passed
Push — develop ( a3afc7...bb6909 )
by nguereza
01:39
created

PlatineTestCase::createFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
/**
4
 * Platine Dev Tools
5
 *
6
 * Platine Dev Tools is a collection of some classes/functions
7
 * designed for development
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Dev Tools
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file PlatineTestCase.php
34
 *
35
 *  The Base class used for test case
36
 *
37
 *  @package    Platine\Dev
38
 *  @author Platine Developers Team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Dev;
49
50
use InvalidArgumentException;
51
use org\bovigo\vfs\vfsStream;
52
use org\bovigo\vfs\vfsStreamContainer;
53
use org\bovigo\vfs\vfsStreamDirectory;
54
use org\bovigo\vfs\vfsStreamFile;
55
use PHPUnit\Framework\TestCase;
56
use ReflectionClass;
57
use ReflectionProperty;
58
use VirtualFileSystem\Structure\Directory;
59
use VirtualFileSystem\Structure\File;
60
61
/**
62
 * @class PlatineTestCase
63
 * @package Platine\Dev
64
 */
65
class PlatineTestCase extends TestCase
66
{
67
    /**
68
     * @codeCoverageIgnore
69
     * @return void
70
     */
71
    protected function tearDown(): void
72
    {
73
        //restore all mock variable global value to "false"
74
        foreach ($GLOBALS as $key => $value) {
75
            if (substr((string) $key, 0, 5) === 'mock_') {
76
                $GLOBALS[$key] = false;
77
            }
78
        }
79
    }
80
81
    /**
82
     * Method to test private & protected method
83
     *
84
     * @param object $object the class instance to use
85
     * @param string $method the name of the method
86
     * @param array<int, mixed> $args the list of method arguments
87
     * @return mixed
88
     */
89
    public function runPrivateProtectedMethod(
90
        object $object,
91
        string $method,
92
        array $args = []
93
    ) {
94
        $reflection = new ReflectionClass(get_class($object));
95
        $reflectionMethod = $reflection->getMethod($method);
96
        $reflectionMethod->setAccessible(true);
97
        return $reflectionMethod->invokeArgs($object, $args);
98
    }
99
100
    /**
101
     * Method to set/get private & protected attribute
102
     *
103
     * @param string $className the name of the class
104
     * @param string $attr the name of the class attribute
105
     */
106
    public function getPrivateProtectedAttribute(
107
        string $className,
108
        string $attr
109
    ): ReflectionProperty {
110
        $rProp = new ReflectionProperty($className, $attr);
111
        $rProp->setAccessible(true);
112
        return $rProp;
113
    }
114
115
    /**
116
     * Create virtual file with the given content
117
     * @param  string $filename
118
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
119
     * @param  string $content
120
     * @return vfsStreamFile
121
     */
122
    public function createVfsFile(
123
        string $filename,
124
        vfsStreamContainer $destination,
125
        string $content = ''
126
    ): vfsStreamFile {
127
        return vfsStream::newFile($filename)
128
                        ->at($destination)
129
                        ->setContent($content);
130
    }
131
132
    /**
133
     * Create virtual file without content
134
     * @param  string $filename
135
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
136
     * @return vfsStreamFile
137
     */
138
    public function createVfsFileOnly(
139
        string $filename,
140
        vfsStreamContainer $destination
141
    ): vfsStreamFile {
142
        return vfsStream::newFile($filename)
143
                        ->at($destination);
144
    }
145
146
    /**
147
     * Create virtual directory
148
     * @param  string $name
149
     * @param  vfsStreamContainer<vfsStreamContainerIterator> $destination
150
     * @return vfsStreamDirectory
151
     */
152
    public function createVfsDirectory(
153
        string $name,
154
        vfsStreamContainer $destination = null
155
    ): vfsStreamDirectory {
156
        if ($destination) {
157
            return vfsStream::newDirectory($name)->at($destination);
158
        }
159
        return vfsStream::newDirectory($name);
160
    }
161
162
    /**
163
     * Create new virtual file
164
     * @param string $filename
165
     * @param string|null $content
166
     * @return File
167
     */
168
    public function createFile(string $filename, ?string $content = null): File
169
    {
170
        $fs = new PlatineFileSystem();
171
        return $fs->createFile($filename, $content);
172
    }
173
174
    /**
175
     * Create new virtual directory
176
     * @param string $path
177
     * @param bool $recursive
178
     * @param int|null $mode
179
     * @return Directory
180
     */
181
    public function createDirectory(string $path, bool $recursive = false, ?int $mode = null): Directory
182
    {
183
        $fs = new PlatineFileSystem();
184
185
        return $fs->createDirectory($path, $recursive, $mode);
186
    }
187
188
    /**
189
     * Return the list of methods to mocks in the parameters of PHPUnit::TestCase::getMock()
190
     *
191
     * @param class-string<object>|object $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<object>|object at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<object>|object.
Loading history...
192
     * @param string[] $exclude list of methods to exclude
193
     * @return string[]
194
     */
195
    public function getClassMethodsToMock($class, array $exclude = []): array
196
    {
197
        $methods = [];
198
199
        if (is_string($class) && !class_exists($class)) {
200
            throw new InvalidArgumentException(
201
                sprintf('Can not find class [%s]', $class)
202
            );
203
        }
204
205
        $reflectionClass = new ReflectionClass($class);
206
207
        foreach ($reflectionClass->getMethods() as $reflectionMethod) {
208
            if (!in_array($reflectionMethod->name, $exclude)) {
209
                $methods[] = $reflectionMethod->name;
210
            }
211
        }
212
213
        return $methods;
214
    }
215
216
    /**
217
     * Get the instance of the given class
218
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
219
     * @param array<string, mixed> $mockMethods
220
     * @param array<int, string> $excludes
221
     * @return mixed
222
     */
223
    public function getMockInstance(
224
        string $class,
225
        array $mockMethods = [],
226
        array $excludes = []
227
    ) {
228
        $methods = $this->getClassMethodsToMock($class, $excludes);
229
230
        $mock = $this->getMockBuilder($class)
231
                    ->disableOriginalConstructor()
232
                    ->onlyMethods($methods)
233
                    ->getMock();
234
235
        foreach ($mockMethods as $method => $returnValue) {
236
            $mock->expects($this->any())
237
                ->method($method)
238
                ->will($this->returnValue($returnValue));
239
        }
240
241
        return $mock;
242
    }
243
244
    /**
245
     * Get the instance of the given class using return map
246
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
247
     * @param array<string, mixed> $mockMethods
248
     * @param array<int, string> $excludes
249
     * @return mixed
250
     */
251
    public function getMockInstanceMap(
252
        string $class,
253
        array $mockMethods = [],
254
        array $excludes = []
255
    ) {
256
        $methods = $this->getClassMethodsToMock($class, $excludes);
257
258
        $mock = $this->getMockBuilder($class)
259
                    ->disableOriginalConstructor()
260
                    ->onlyMethods($methods)
261
                    ->getMock();
262
263
        foreach ($mockMethods as $method => $returnValues) {
264
            $mock->expects($this->any())
265
                ->method($method)
266
                ->will(
267
                    $this->returnValueMap($returnValues)
268
                );
269
        }
270
271
        return $mock;
272
    }
273
274
    /**
275
     * Return the value of private or protected property
276
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
277
     * @param object $instance
278
     * @param string $name
279
     * @return mixed
280
     */
281
    public function getPropertyValue(string $class, object $instance, string $name)
282
    {
283
        $reflection = $this->getPrivateProtectedAttribute($class, $name);
284
        return $reflection->getValue($instance);
285
    }
286
287
    /**
288
     * Set the value of private or protected property
289
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
290
     * @param object $instance
291
     * @param string $name
292
     * @param mixed $value
293
     * @return void
294
     */
295
    public function setPropertyValue(string $class, object $instance, string $name, $value)
296
    {
297
        $reflection = $this->getPrivateProtectedAttribute($class, $name);
298
        $reflection->setValue($instance, $value);
299
    }
300
301
    /**
302
     * Test assert command expected given output
303
     * @param string $expected
304
     * @param string $output
305
     * @return void
306
     */
307
    public function assertCommandOutput(string $expected, string $output): void
308
    {
309
        $result = str_replace("\n", PHP_EOL, $expected);
310
        $this->assertEquals($result, $output);
311
    }
312
}
313