Completed
Push — master ( 80d5dd...e32bbf )
by Vladimir
03:02
created

PHPUnit_Stakx_TestCase::getReadableLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Test;
9
10
use allejo\stakx\Command\BuildableCommand;
11
use allejo\stakx\Configuration;
12
use allejo\stakx\Core\StakxLogger;
13
use allejo\stakx\Filesystem\File;
14
use allejo\stakx\Manager\CollectionManager;
15
use allejo\stakx\Service;
16
use allejo\stakx\System\Filesystem;
17
use allejo\stakx\Filesystem\Folder;
18
use org\bovigo\vfs\vfsStream;
19
use org\bovigo\vfs\vfsStreamDirectory;
20
use org\bovigo\vfs\vfsStreamFile;
21
use Psr\Log\LoggerInterface;
22
use Symfony\Component\Console\Output\ConsoleOutput;
23
use Symfony\Component\Yaml\Yaml;
24
25
abstract class PHPUnit_Stakx_TestCase extends \PHPUnit_Framework_TestCase
0 ignored issues
show
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
26
{
27
    const FM_OBJ_TEMPLATE = "---\n%s\n---\n\n%s";
28
29
    /** @var string */
30
    protected $assetFolder;
31
    /** @var vfsStreamFile */
32
    protected $dummyFile;
33
    /** @var vfsStreamDirectory */
34
    protected $rootDir;
35
    /** @var Filesystem */
36
    protected $fs;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $fs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
37
38
    public function setUp()
39
    {
40
        $this->dummyFile = vfsStream::newFile('stakx.html.twig');
41
        $this->rootDir = vfsStream::setup();
42
        $this->fs = new Filesystem();
43
44
        Service::setParameter(BuildableCommand::USE_DRAFTS, false);
45
        Service::setParameter(BuildableCommand::WATCHING, false);
46
        Service::setParameter(Configuration::HIGHLIGHTER_ENABLED, true);
47
        Service::setParameter('build.preserveCase', false);
48
49
        // Inspect the VFS as an array
50
        // vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure();
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
51
    }
52
53
    public function tearDown()
54
    {
55
        if ($this->assetFolder !== null)
56
        {
57
            $this->fs->remove($this->assetFolder);
58
        }
59
    }
60
61
    ///
62
    // Assertion functions
63
    ///
64
65
    /**
66
     * @param string $needle
67
     * @param string $haystack
68
     * @param string $message
69
     */
70
    protected function assertStringContains($needle, $haystack, $message = '')
71
    {
72
        $this->assertNotFalse(strpos($haystack, $needle), $message);
73
    }
74
75
    protected function assertFileContains($fileContent, $filePath, $message = '')
76
    {
77
        (substr($filePath, -1, 1) == '/') && $filePath .= 'index.html';
78
79
        $contents = file_get_contents($filePath);
80
81
        $this->assertStringContains($fileContent, $contents, $message);
82
    }
83
84
    ///
85
    // Utility Functions
86
    ///
87
88
    protected function bookCollectionProvider($jailed = false)
89
    {
90
        $cm = new CollectionManager();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cm. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
91
        $cm->setLogger($this->getMockLogger());
92
        $cm->parseCollections(array(
93
            array(
94
                'name' => 'books',
95
                'folder' => 'tests/allejo/stakx/Test/assets/MyBookCollection/',
96
            ),
97
        ));
98
99
        return (!$jailed) ? $cm->getCollections() : $cm->getJailedCollections();
100
    }
101
102
    /**
103
     * Write a temporary file to the asset folder.
104
     *
105
     * This file will be written to the actual filesystem and not the virtual filesystem.
106
     *
107
     * @param $fileName
108
     * @param $content
109
     *
110
     * @return string Path to the temporary file; relative to the project's root
111
     */
112
    protected function createTempFile($fileName, $content)
113
    {
114
        $folder = new Folder($this->assetFolder);
115
        $folder->writeFile($fileName, $content);
116
117
        return $this->fs->appendPath($this->assetFolder, $fileName);
118
    }
119
120
    /**
121
     * Create a blank file on the virtual filesystem.
122
     *
123
     * @param string $filename
124
     * @param string $classType
125
     * @param string $content
126
     *
127
     * @return mixed
128
     */
129
    protected function createBlankFile($filename, $classType, $content)
130
    {
131
        $file = vfsStream::newFile($filename);
132
        $file
133
            ->setContent($content)
134
            ->at($this->rootDir);
135
136
        $url = $file->url();
137
138
        return new $classType($this->createFileObjectFromPath($url));
139
    }
140
141
    /**
142
     * Create a virtual file following the a FrontMatter-ready template.
143
     *
144
     * @param string $classType
145
     * @param array  $frontMatter
146
     * @param string $body
147
     *
148
     * @return mixed
149
     */
150
    protected function createVirtualFrontMatterFile($classType, $frontMatter = array(), $body = 'Body Text')
151
    {
152
        return new $classType($this->setAndCreateVirtualFrontMatterFileObject($frontMatter, $body));
153
    }
154
155
    /**
156
     * Set the contents of our default virtual file and create a File object for it.
157
     *
158
     * @param array  $frontMatter
159
     * @param string $body
160
     *
161
     * @return File
162
     */
163
    protected function setAndCreateVirtualFrontMatterFileObject($frontMatter = array(), $body = 'Body Text')
164
    {
165
        $this->dummyFile
166
            ->setContent($this->buildFrontMatterTemplate($frontMatter, $body))
167
            ->at($this->rootDir);
168
169
        return $this->createFileObjectFromPath($this->dummyFile->url());
170
    }
171
172
    /**
173
     * Create multiple virtual files from a given array of information.
174
     *
175
     * @param string $classType
176
     * @param array  $elements
177
     *
178
     * @return array
179
     */
180
    protected function createMultipleVirtualFiles($classType, $elements)
181
    {
182
        $results = array();
183
184
        foreach ($elements as $element)
185
        {
186
            $filename = (isset($element['filename'])) ? $element['filename'] : hash('sha256', uniqid(mt_rand(), true), false);
187
            $frontMatter = (empty($element['frontmatter'])) ? '' : Yaml::dump($element['frontmatter'], 2);
188
            $body = (isset($element['body'])) ? $element['body'] : 'Body Text';
189
190
            $file = vfsStream::newFile($filename);
191
            $file
192
                ->setContent(sprintf("---\n%s\n---\n\n%s", $frontMatter, $body))
193
                ->at($this->rootDir);
194
195
            $url = $file->url();
196
197
            $results[] = new $classType($this->createFileObjectFromPath($url));
198
        }
199
200
        return $results;
201
    }
202
203
    /**
204
     * Create a File object from a given path.
205
     *
206
     * @param  string $filePath
207
     *
208
     * @return File
209
     */
210
    protected function createFileObjectFromPath($filePath)
211
    {
212
        return (new File(
213
            $filePath,
214
            $this->fs->getFolderPath($filePath),
215
            $filePath
216
        ));
217
    }
218
219
    /**
220
     * Generate a FrontMatter-ready syntax to be used as a file's content.
221
     *
222
     * @param array  $frontMatter
223
     * @param string $body
224
     *
225
     * @return string
226
     */
227
    protected function buildFrontMatterTemplate(array $frontMatter = array(), $body = 'Body text')
228
    {
229
        $fm = (empty($frontMatter)) ? '' : Yaml::dump($frontMatter, 2);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $fm. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
230
231
        return sprintf(self::FM_OBJ_TEMPLATE, $fm, $body);
232
    }
233
234
    /**
235
     * Get a mock logger.
236
     *
237
     * @return LoggerInterface
238
     */
239
    protected function getMockLogger()
240
    {
241
        return $this->getMock(LoggerInterface::class);
242
    }
243
244
    /**
245
     * Get a real logger instance that will save output to the console.
246
     *
247
     * @return StakxLogger
248
     */
249
    protected function getReadableLogger()
250
    {
251
        stream_filter_register('intercept', StreamInterceptor::class);
252
        $stakxLogger = new StakxLogger(new ConsoleOutput());
253
        stream_filter_append($stakxLogger->getOutputInterface()->getStream(), 'intercept');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Output\OutputInterface as the method getStream() does only exist in the following implementations of said interface: Symfony\Component\Console\Output\ConsoleOutput, Symfony\Component\Console\Output\StreamOutput.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
254
255
        return $stakxLogger;
256
    }
257
258
    /**
259
     * Create a temporary folder where temporary file writes will be made to.
260
     *
261
     * @param string $folderName
262
     */
263
    protected function createAssetFolder($folderName)
264
    {
265
        $this->assetFolder = $this->fs->getRelativePath($this->fs->appendPath(__DIR__, $folderName));
266
267
        $this->fs->mkdir($this->assetFolder);
268
    }
269
}
270