Completed
Pull Request — master (#16)
by Sergii
03:45
created

DrupalKernelPlaceholder::formatString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
6
use Behat\Behat\Hook\Scope\BeforeFeatureScope;
7
use Drupal\TqExtension\Utils\Database\FetchField;
8
9
// @codingStandardsIgnoreStart
10
final class DrupalKernelPlaceholder extends DrupalKernelPlaceholderBase
11
  // @codingStandardsIgnoreEnd
12
{
13
    /**
14
     * {@inheritdoc}
15
     */
16
    public static function beforeFeature(BeforeFeatureScope $scope)
17
    {
18
        // Set to "false", because the administration menu will not be rendered.
19
        // @see https://www.drupal.org/node/2023625#comment-8607207
20
        variable_set('admin_menu_cache_client', false);
21
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public static function t($string, array $args = [], array $options = [])
27
    {
28
        return t($string, $args, $options);
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public static function arg()
35
    {
36
        return arg();
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public static function formatString($string, array $args = [])
43
    {
44
        return format_string($string, $args);
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public static function tokenReplace($text, array $data = [], array $options = [])
51
    {
52
        return token_replace($text, $data, $options);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public static function sitePath()
59
    {
60
        return conf_path();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public static function jsonEncode($data)
67
    {
68
        return drupal_json_encode($data);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     *
74
     * @param \stdClass $user
75
     */
76
    public static function setCurrentUser($user)
1 ignored issue
show
Coding Style introduced by
setCurrentUser uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
77
    {
78
        $GLOBALS['user'] = $user;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public static function setCurrentPath($path)
1 ignored issue
show
Coding Style introduced by
setCurrentPath uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
85
    {
86
        $_GET['q'] = $path;
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public static function getUidByName($username)
93
    {
94
        return (int) (new FetchField('users', 'uid'))
95
            ->condition('name', $username)
96
            ->execute();
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public static function deleteUser($user_id)
103
    {
104
        user_delete($user_id);
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     *
110
     * @return \SelectQuery
111
     */
112
    public static function selectQuery($table, $alias = null, array $options = [])
113
    {
114
        return db_select($table, $alias, $options);
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120
    public static function getFieldDefinitions($entityType, $bundle)
121
    {
122
        $definitions = [];
123
124
        foreach (field_info_instances($entityType, $bundle) as $name => $definition) {
125
            $definitions[$name] = [
126
                'label' => $definition['label'],
127
                'required' => $definition['required'],
128
            ];
129
        }
130
131
        return $definitions;
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public static function entityLoad($entityType, $id)
138
    {
139
        return entity_metadata_wrapper($entityType, $id);
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     *
145
     * @param \EntityDrupalWrapper $entity
146
     */
147
    public static function entityHasField($entity, $fieldName)
148
    {
149
        return isset($entity->{$fieldName});
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     *
155
     * @param \EntityDrupalWrapper $entity
156
     */
157
    public static function entityFieldValue($entity, $fieldName)
158
    {
159
        return $entity->{$fieldName}->value();
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     */
165
    public static function switchMailSystem($useTesting)
166
    {
167
        static $original = [
168
            'default-system' => 'DefaultMailSystem',
169
        ];
170
171
        if ($useTesting) {
172
            // Store original mail system to restore it after scenario.
173
            $original = variable_get('mail_system', $original);
174
            // Set the mail system for testing. It will store an emails in
175
            // "drupal_test_email_collector" Drupal variable instead of sending.
176
            $value = array_merge($original, [
177
                'default-system' => 'TestingMailSystem',
178
            ]);
179
        } else {
180
            // Bring back the original mail system.
181
            $value = $original;
182
            // Flush the email buffer to be able to reuse it from scratch.
183
            // @see \TestingMailSystem
184
            variable_set('drupal_test_email_collector', []);
185
        }
186
187
        variable_set('mail_system', $value);
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public static function getEmailMessages()
194
    {
195
        // We can't use variable_get() because Behat has another bootstrapped
196
        // variable $conf that is not updated from cURL bootstrapped Drupal instance.
197
        $result = (new FetchField('variable', 'value'))
198
            ->condition('name', 'drupal_test_email_collector')
199
            ->execute();
200
201
        return empty($result) ? [] : unserialize($result);
202
    }
203
204
    /**
205
     * {@inheritdoc}
206
     */
207
    public static function getContentTypeName($contentType)
208
    {
209
        if (isset(node_type_get_types()[$contentType])) {
210
            return $contentType;
211
        }
212
213
        return (string) (new FetchField('node_type', 'type'))
214
            ->condition('name', $contentType)
215
            ->execute();
216
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221
    public static function injectCustomJavascript($file, $delete = false)
222
    {
223
        $file .= '.js';
224
        $modulePath = static::drupalGetFilename('module', 'system');
225
        $destination = dirname($modulePath) . '/' . $file;
226
        $injection = "\ndrupal_add_js('$destination', array('every_page' => TRUE));";
227
228
        if ($delete) {
229
            static::fileUnmanagedDelete($destination);
230
231
            $search = $injection;
232
            $replace = '';
233
        } else {
234
            static::fileUnmanagedCopy(
235
                str_replace('Context', 'JavaScript', __DIR__) . '/' . $file,
236
                $destination,
237
                FILE_EXISTS_REPLACE
238
            );
239
240
            $search = 'system_add_module_assets();';
241
            $replace = $search . $injection;
242
        }
243
244
        file_put_contents($modulePath, str_replace($search, $replace, file_get_contents($modulePath)));
245
    }
246
}
247