Completed
Pull Request — master (#42)
by Vladimir
02:38
created

PHPUnit_Stakx_TestCase::assertStringContains()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 4
rs 10
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\Core\StakxLogger;
11
use allejo\stakx\Manager\CollectionManager;
12
use allejo\stakx\System\Filesystem;
13
use allejo\stakx\System\Folder;
14
use org\bovigo\vfs\vfsStream;
15
use org\bovigo\vfs\vfsStreamDirectory;
16
use org\bovigo\vfs\vfsStreamFile;
17
use Psr\Log\LoggerInterface;
18
use Symfony\Component\Console\Output\ConsoleOutput;
19
use Symfony\Component\Yaml\Yaml;
20
21
abstract class PHPUnit_Stakx_TestCase extends \PHPUnit_Framework_TestCase
0 ignored issues
show
Coding Style introduced by
PHPUnit_Stakx_TestCase does not seem to conform to the naming convention (^[A-Z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Coding Style introduced by
PHPUnit_Stakx_TestCase does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
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...
22
{
23
    const FM_OBJ_TEMPLATE = "---\n%s\n---\n\n%s";
24
25
    /** @var string */
26
    protected $assetFolder;
27
28
    /**
29
     * @var vfsStreamFile
30
     */
31
    protected $dummyFile;
32
33
    /**
34
     * @var vfsStreamDirectory
35
     */
36
    protected $rootDir;
37
38
    /**
39
     * @var Filesystem
40
     */
41
    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...
42
43
    public function setUp()
44
    {
45
        $this->dummyFile = vfsStream::newFile('stakx.html.twig');
46
        $this->rootDir = vfsStream::setup();
47
        $this->fs = new Filesystem();
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
    ///
54
    // Assertion functions
55
    ///
56
57
    protected function assertStringContains($needle, $haystack, $message = '')
58
    {
59
        $this->assertNotFalse(strpos($haystack, $needle), $message);
60
    }
61
62
    protected function assertFileContains($fileContent, $filePath, $message = '')
63
    {
64
        (substr($filePath, -1, 1) == '/') && $filePath .= 'index.html';
65
66
        $contents = file_get_contents($filePath);
67
68
        $this->assertStringContains($fileContent, $contents, $message);
69
    }
70
71
    ///
72
    // Utility Functions
73
    ///
74
75
    protected function bookCollectionProvider($jailed = false)
76
    {
77
        $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...
78
        $cm->setLogger($this->getMockLogger());
79
        $cm->parseCollections(array(
80
            array(
81
                'name' => 'books',
82
                'folder' => 'tests/allejo/stakx/Test/assets/MyBookCollection/',
83
            ),
84
        ));
85
86
        return (!$jailed) ? $cm->getCollections() : $cm->getJailedCollections();
87
    }
88
89
    /**
90
     * @param string $classType
91
     * @param array  $frontMatter
92
     * @param string $body
93
     *
94
     * @return mixed
95
     */
96
    protected function createVirtualFile($classType, $frontMatter = array(), $body = 'Body Text')
97
    {
98
        $this->dummyFile
99
            ->setContent($this->generateFM($frontMatter, $body))
100
            ->at($this->rootDir);
101
102
        return new $classType($this->dummyFile->url());
103
    }
104
105
    protected function createMultipleVirtualFiles($classType, $elements)
106
    {
107
        $results = array();
108
109
        foreach ($elements as $element) {
110
            $filename = (isset($element['filename'])) ? $element['filename'] : hash('sha256', uniqid(mt_rand(), true), false);
111
            $frontMatter = (empty($element['frontmatter'])) ? '' : Yaml::dump($element['frontmatter'], 2);
112
            $body = (isset($element['body'])) ? $element['body'] : 'Body Text';
113
114
            $file = vfsStream::newFile($filename);
115
            $file
116
                ->setContent(sprintf("---\n%s\n---\n\n%s", $frontMatter, $body))
117
                ->at($this->rootDir);
118
119
            $results[] = new $classType($file->url());
120
        }
121
122
        return $results;
123
    }
124
125
    /**
126
     * Get a mock logger.
127
     *
128
     * @return LoggerInterface
129
     */
130
    protected function getMockLogger()
131
    {
132
        return $this->getMock(LoggerInterface::class);
133
    }
134
135
    /**
136
     * Get a real logger instance that will save output to the console.
137
     *
138
     * @return StakxLogger
139
     */
140
    protected function getReadableLogger()
141
    {
142
        stream_filter_register('intercept', StreamInterceptor::class);
143
        $stakxLogger = new StakxLogger(new ConsoleOutput());
144
        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...
145
146
        return $stakxLogger;
147
    }
148
149
    /**
150
     * Generate a FrontMatter-ready syntax to be used as a file's content.
151
     *
152
     * @param array  $frontMatter
153
     * @param string $body
154
     *
155
     * @return string
156
     */
157
    protected function generateFM(array $frontMatter = array(), $body = 'Body text')
158
    {
159
        $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...
160
161
        return sprintf(self::FM_OBJ_TEMPLATE, $fm, $body);
162
    }
163
164
    /**
165
     * Create a temporary folder where temporary file writes will be made to
166
     *
167
     * Remember to remove the folder in during the ::tearDown()
168
     *
169
     * @param string $folderName
170
     */
171
    protected function createAssetFolder($folderName)
172
    {
173
        $this->assetFolder = $this->fs->getRelativePath($this->fs->appendPath(__DIR__, $folderName));
174
175
        $this->fs->mkdir($this->assetFolder);
176
    }
177
178
    /**
179
     * Write a temporary file to the asset folder
180
     *
181
     * @param $fileName
182
     * @param $content
183
     *
184
     * @return string Path to the temporary file; relative to the project's root
185
     */
186
    protected function writeTempFile($fileName, $content)
187
    {
188
        $folder = new Folder($this->assetFolder);
189
        $folder->writeFile($fileName, $content);
190
191
        return $this->fs->appendPath($this->assetFolder, $fileName);
192
    }
193
}
194