Completed
Pull Request — master (#41)
by Vladimir
02:18
created

createMultipleVirtualFiles()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 9
nop 2
dl 0
loc 20
rs 8.8571
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 org\bovigo\vfs\vfsStream;
14
use org\bovigo\vfs\vfsStreamDirectory;
15
use org\bovigo\vfs\vfsStreamFile;
16
use Psr\Log\LoggerInterface;
17
use Symfony\Component\Console\Output\ConsoleOutput;
18
use Symfony\Component\Yaml\Yaml;
19
20
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...
21
{
22
    const FM_OBJ_TEMPLATE = "---\n%s\n---\n\n%s";
23
24
    /**
25
     * @var vfsStreamFile
26
     */
27
    protected $dummyFile;
28
29
    /**
30
     * @var vfsStreamDirectory
31
     */
32
    protected $rootDir;
33
34
    /**
35
     * @var Filesystem
36
     */
37
    protected $fs;
38
39
    public function setUp()
40
    {
41
        $this->dummyFile    = vfsStream::newFile('stakx.html.twig');
42
        $this->rootDir      = vfsStream::setup();
43
        $this->fs           = new Filesystem();
44
    }
45
46
    //
47
    // Assert Functions
48
    //
49
50
    public function assertFileExistsAndContains ($filePath, $needle, $message = '')
51
    {
52
        $this->assertFileExists($filePath, $message);
53
54
        $contents = file_get_contents($filePath);
55
56
        $this->assertContains($needle, $contents, $message);
57
    }
58
59
    //
60
    // Utility Functions
61
    //
62
63
    protected function bookCollectionProvider ($jailed = false)
64
    {
65
        $cm = new CollectionManager();
66
        $cm->setLogger($this->getMockLogger());
67
        $cm->parseCollections(array(
68
            array(
69
                'name'   => 'books',
70
                'folder' => 'tests/allejo/stakx/Test/assets/MyBookCollection/'
71
            )
72
        ));
73
74
        return ($jailed) ? $cm->getCollections() : $cm->getJailedCollections();
75
    }
76
77
    /**
78
     * @param  string $classType
79
     * @param  array  $frontMatter
80
     * @param  string $body
81
     *
82
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use object.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
83
     */
84
    protected function createVirtualFile ($classType, $frontMatter = array(), $body = "Body Text")
85
    {
86
        $fm = (empty($frontMatter)) ? '' : Yaml::dump($frontMatter, 2);
87
88
        $this->dummyFile
89
            ->setContent(sprintf("---\n%s\n---\n\n%s", $fm, $body))
90
            ->at($this->rootDir);
91
92
        return (new $classType($this->dummyFile->url()));
93
    }
94
95
    protected function createMultipleVirtualFiles ($classType, $elements)
96
    {
97
        $results = array();
98
99
        foreach ($elements as $element)
100
        {
101
            $filename = (isset($element['filename'])) ? $element['filename'] : hash('sha256', uniqid(mt_rand(), true), false);
102
            $frontMatter = (empty($element['frontmatter'])) ? '' : Yaml::dump($element['frontmatter'], 2);
103
            $body = (isset($element['body'])) ? $element['body'] : 'Body Text';
104
105
            $file = vfsStream::newFile($filename);
106
            $file
107
                ->setContent(sprintf("---\n%s\n---\n\n%s", $frontMatter, $body))
108
                ->at($this->rootDir);
109
110
            $results[] = new $classType($file->url());
111
        }
112
113
        return $results;
114
    }
115
116
    /**
117
     * Get a mock logger
118
     *
119
     * @return LoggerInterface
120
     */
121
    protected function getMockLogger ()
122
    {
123
        return $this->getMock(LoggerInterface::class);
124
    }
125
126
    /**
127
     * Get a real logger instance that will save output to the console
128
     *
129
     * @return StakxLogger
130
     */
131
    protected function getReadableLogger ()
132
    {
133
        stream_filter_register('intercept', StreamInterceptor::class);
134
        $stakxLogger = new StakxLogger(new ConsoleOutput());
135
        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...
136
137
        return $stakxLogger;
138
    }
139
}