Completed
Pull Request — master (#105)
by
unknown
08:51
created

FeatureContext   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 99
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
lcom 1
cbo 9
dl 0
loc 99
rs 10
c 1
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 31 4
A setMinkParameters() 0 7 2
A getFixtureFactory() 0 7 2
A setFixtureFactory() 0 3 1
A getTestSessionState() 0 11 1
A getFakeDatabasePath() 0 3 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
68
    public function setMinkParameters(array $parameters) {
69
        parent::setMinkParameters($parameters);
70
        
71
        if(isset($parameters['files_path'])) {
72
            $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...
73
        }
74
    }
75
76
    /**
77
     * @return FixtureFactory
78
     */
79
    public function getFixtureFactory() {
80
        if(!$this->fixtureFactory) {
81
            $this->fixtureFactory = \Injector::inst()->create('BehatFixtureFactory');
82
        }
83
84
        return $this->fixtureFactory;
85
    }
86
87
    public function setFixtureFactory(FixtureFactory $factory) {
88
        $this->fixtureFactory = $factory;
89
    }
90
91
    /**
92
     * "Shares" the database with web requests, see
93
     * {@link MeridianFakeManagerControllerExtension}
94
     */
95
    public function getTestSessionState() {
96
        return array_merge(
97
            parent::getTestSessionState(),
98
            array(
99
                'useFakeManager' => true,
100
                'importDatabasePath' => BASE_PATH .'/mysite/tests/fixtures/SS-sample.sql',
101
                'requireDefaultRecords' => false,
102
                'fakeDatabasePath' => $this->getFakeDatabasePath(),
103
            )
104
        );
105
    }
106
107
    public function getFakeDatabasePath() {
108
        return BASE_PATH . '/FakeDatabase.json';
109
    }
110
    //
111
    // Place your definition and hook methods here:
112
    //
113
    //    /**
114
    //     * @Given /^I have done something with "([^"]*)"$/
115
    //     */
116
    //    public function iHaveDoneSomethingWith($argument) {
117
    //        $container = $this->kernel->getContainer();
118
    //        $container->get('some_service')->doSomethingWith($argument);
119
    //    }
120
    //
121
}
122