Completed
Pull Request — master (#105)
by
unknown
02:10
created

FeatureContext::__construct()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 43
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 43
rs 8.5806
cc 4
eloc 25
nc 2
nop 1
1
<?php
2
3
namespace Mysite\Test\Behaviour;
4
5
use SilverStripe\BehatExtension\Context\SilverStripeContext,
6
    SilverStripe\BehatExtension\Context\BasicContext,
7
    SilverStripe\BehatExtension\Context\LoginContext,
8
    SilverStripe\BehatExtension\Context\FixtureContext,
9
    SilverStripe\Framework\Test\Behaviour\CmsFormsContext,
10
    SilverStripe\Framework\Test\Behaviour\CmsUiContext,
11
    SilverStripe\Cms\Test\Behaviour;
12
13
// PHPUnit
14
require_once 'PHPUnit/Autoload.php';
15
require_once 'PHPUnit/Framework/Assert/Functions.php';
16
17
/**
18
 * Features context
19
 *
20
 * Context automatically loaded by Behat.
21
 * Uses subcontexts to extend functionality.
22
 */
23
class FeatureContext extends SilverStripeContext {
24
    
25
    /**
26
     * @var FixtureFactory
27
     */
28
    protected $fixtureFactory;
29
30
    /**
31
     * Initializes context.
32
     * Every scenario gets it's own context object.
33
     *
34
     * @param array $parameters context parameters (set them up through behat.yml)
35
     */
36
    public function __construct(array $parameters) {
37
        parent::__construct($parameters);
38
39
        $this->useContext('BasicContext', new BasicContext($parameters));
40
        $this->useContext('LoginContext', new LoginContext($parameters));
41
        $this->useContext('CmsFormsContext', new CmsFormsContext($parameters));
42
        $this->useContext('CmsUiContext', new CmsUiContext($parameters));
43
44
        $fixtureContext = new FixtureContext($parameters);
45
        $fixtureContext->setFixtureFactory($this->getFixtureFactory());
46
        $this->useContext('FixtureContext', $fixtureContext);
47
48
        // Use blueprints to set user name from identifier
49
        $factory = $fixtureContext->getFixtureFactory();
50
        $blueprint = \Injector::inst()->create('FixtureBlueprint', 'Member');
51
        $blueprint->addCallback('beforeCreate', function($identifier, &$data, &$fixtures) {
0 ignored issues
show
Unused Code introduced by
The parameter $fixtures is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
52
            if(!isset($data['FirstName'])) $data['FirstName'] = $identifier;
53
        });
54
        $factory->define('Member', $blueprint);
55
56
        // Auto-publish pages
57
        if (class_exists('SiteTree')) {
58
            foreach(\ClassInfo::subclassesFor('SiteTree') as $id => $class) {
0 ignored issues
show
Bug introduced by
The expression \ClassInfo::subclassesFor('SiteTree') of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
59
                $blueprint = \Injector::inst()->create('FixtureBlueprint', $class);
60
                $blueprint->addCallback('afterCreate', function($obj, $identifier, &$data, &$fixtures) {
0 ignored issues
show
Unused Code introduced by
The parameter $identifier is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $fixtures is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
                    $obj->publish('Stage', 'Live');
62
                });
63
                $factory->define($class, $blueprint);
64
            }
65
        }
66
67
        $manager = \Injector::inst()->get(
68
            'FakeManager',
69
            true,
70
            // Creates a new database automatically. Session doesn't exist here yet,
71
            // so we need to take fake database path from internal config.
72
            // The same path is then set in the browser session
73
            // and reused across scenarios (see resetFakeDatabase()).
74
            array(new \FakeDatabase($this->getFakeDatabasePath()))
75
        );
76
        
77
        $this->manager = $manager;
0 ignored issues
show
Bug introduced by
The property manager does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
78
    }
79
80
    public function setMinkParameters(array $parameters) {
81
        parent::setMinkParameters($parameters);
82
        
83
        if(isset($parameters['files_path'])) {
84
            $this->getSubcontext('FixtureContext')->setFilesPath($parameters['files_path']);    
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method setFilesPath() does only exist in the following implementations of said interface: SilverStripe\BehatExtension\Context\FixtureContext.

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...
85
        }
86
    }
87
88
    /**
89
     * @return FixtureFactory
90
     */
91
    public function getFixtureFactory() {
92
        if(!$this->fixtureFactory) {
93
            $this->fixtureFactory = \Injector::inst()->create('BehatFixtureFactory');
94
        }
95
96
        return $this->fixtureFactory;
97
    }
98
99
    public function setFixtureFactory(FixtureFactory $factory) {
100
        $this->fixtureFactory = $factory;
101
    }
102
103
    /**
104
     * "Shares" the database with web requests, see
105
     * {@link MeridianFakeManagerControllerExtension}
106
     */
107
    public function getTestSessionState() {
108
        return array_merge(
109
            parent::getTestSessionState(),
110
            array(
111
                'useFakeManager' => true,
112
                'importDatabasePath' => BASE_PATH .'/mysite/tests/fixtures/SS-sample.sql',
113
                'requireDefaultRecords' => false,
114
                'fakeDatabasePath' => $this->getFakeDatabasePath(),
115
            )
116
        );
117
    }
118
119
    public function getFakeDatabasePath() {
120
        return BASE_PATH . '/FakeDatabase.json';
121
    }
122
    
123
    /**
124
     * @BeforeScenario
125
     */
126
    public function resetFakeDatabase() {
127
        $this->manager->getDb()->reset(true);
128
    }
129
    //
130
    // Place your definition and hook methods here:
131
    //
132
    //    /**
133
    //     * @Given /^I have done something with "([^"]*)"$/
134
    //     */
135
    //    public function iHaveDoneSomethingWith($argument) {
136
    //        $container = $this->kernel->getContainer();
137
    //        $container->get('some_service')->doSomethingWith($argument);
138
    //    }
139
    //
140
}
141