Completed
Pull Request — master (#16)
by Sergii
07:37
created

Drupal8Placeholder::t()   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 3
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Cores;
6
7
use Behat\Behat\Hook\Scope\BeforeFeatureScope;
8
use Drupal\Core\Field\FieldDefinitionInterface;
9
use Drupal\Core\Entity\FieldableEntityInterface;
10
use Drupal\Core\Session\AccountInterface;
11
use Drupal\Core\Database\Database;
12
use Drupal\Core\Database\Query\Select;
13
use Drupal\Core\StringTranslation\TranslatableMarkup;
14
use Drupal\Component\Render\FormattableMarkup;
15
use Drupal\Component\Serialization\Json;
16
use Drupal\TqExtension\Utils\Database\FetchField;
17
18
final class Drupal8Placeholder extends DrupalKernelPlaceholder
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public static function beforeFeature(BeforeFeatureScope $scope)
24
    {
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public static function t($string, array $arguments = [], array $options = [])
31
    {
32
        return (string) new TranslatableMarkup($string, $arguments, $options);
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public static function formatString($string, array $arguments = [])
39
    {
40
        return (string) new FormattableMarkup($string, $arguments);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public static function arg()
47
    {
48
        return explode('/', \Drupal::service('path.current')->getPath());
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public static function tokenReplace($text, array $data = [], array $options = [])
55
    {
56
        return \Drupal::token()->replace($text, $data, $options);
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public static function jsonEncode($data)
63
    {
64
        return Json::encode($data);
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     *
70
     * @return AccountInterface
71
     */
72
    public static function getCurrentUser()
73
    {
74
        return \Drupal::currentUser()->getAccount();
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     *
80
     * @param AccountInterface $user
81
     */
82
    public static function setCurrentUser($user)
83
    {
84
        \Drupal::currentUser()->setAccount($user);
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public static function setCurrentPath($path)
91
    {
92
        \Drupal::service('path.current')->setPath($path);
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public static function getUidByName($username)
99
    {
100
        return (int) (new FetchField('users_field_data', 'uid'))
101
            ->condition('name', $username)
102
            ->execute();
103
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108
    public static function deleteUser($user_id)
109
    {
110
        $user_storage = \Drupal::entityTypeManager()->getStorage('user');
111
        $user_storage->delete([$user_storage->load($user_id)]);
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     *
117
     * @return Select
118
     */
119
    public static function selectQuery($table, $alias = null, array $options = [])
120
    {
121
        return \Drupal::database()->select($table, $alias, $options);
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public static function getFieldDefinitions($entityType, $bundle)
128
    {
129
        $definitions = [];
130
131
        /** @var FieldDefinitionInterface $definition */
132
        foreach (\Drupal::service('entity_field.manager')->getFieldDefinitions($entityType, $bundle) as $name => $definition) {
133
            $definitions[$name] = [
134
                'label' => (string) $definition->getLabel(),
135
                'required' => $definition->isRequired(),
136
            ];
137
        }
138
139
        return $definitions;
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     */
145
    public static function getDatabaseConnectionInfo($connection)
146
    {
147
        return Database::getConnectionInfo($connection);
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public static function entityCreate($entityType, array $values)
154
    {
155
        $entity = \Drupal::entityTypeManager()
156
            ->getStorage($entityType)
157
            ->create($values);
158
159
        $entity->save();
160
161
        return [$entity->id(), $entityType, $entity->bundle()];
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167
    public static function entityLoad($entityType, $id)
168
    {
169
        return \Drupal::entityTypeManager()->getStorage($entityType)->load($id);
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     *
175
     * @param FieldableEntityInterface $entity
176
     */
177
    public static function entityHasField($entity, $fieldName)
178
    {
179
        return $entity->hasField($fieldName);
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     *
185
     * @param FieldableEntityInterface $entity
186
     */
187
    public static function entityFieldValue($entity, $fieldName)
188
    {
189
        if ($entity instanceof FieldableEntityInterface) {
190
            return $entity->get($fieldName)->value;
191
        }
192
193
        throw new \InvalidArgumentException(sprintf(
194
            'First argument for "%s" method must be of "%s" type.',
195
            __METHOD__,
196
            FieldableEntityInterface::class
197
        ));
198
    }
199
200
    /**
201
     * {@inheritdoc}
202
     */
203
    public static function switchMailSystem($useTesting)
204
    {
205
        static $original = 'php_mail';
206
207
        $systemMail = \Drupal::configFactory()
208
          ->getEditable('system.mail');
209
210
        if ($useTesting) {
211
            // Store original mail system to restore it after scenario.
212
            $original = $systemMail->get('interface.default') ?: $original;
213
            // Set the mail system for testing. It will store an emails in
214
            // "system.test_mail_collector" Drupal state instead of sending.
215
            $value = 'test_mail_collector';
216
        } else {
217
            // Bring back the original mail system.
218
            $value = $original;
219
            // Flush the email buffer to be able to reuse it from scratch.
220
            // @see \Drupal\Core\Mail\Plugin\Mail\TestMailCollector
221
            \Drupal::state()->set('system.test_mail_collector', []);
222
        }
223
224
        $systemMail->set('interface.default', $value)->save(true);
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     */
230
    public static function getEmailMessages()
231
    {
232
        return \Drupal::state()->get('system.test_mail_collector') ?: [];
233
    }
234
235
    /**
236
     * {@inheritdoc}
237
     */
238
    public static function getContentTypeName($contentType)
239
    {
240
        $nodeTypeStorage = \Drupal::entityTypeManager()
241
            ->getStorage('node_type');
242
243
        if ($nodeTypeStorage->load($contentType)) {
244
            return $contentType;
245
        }
246
247
        // The result will be like: ['article' => 'article'].
248
        $result = $nodeTypeStorage->getQuery()
249
            ->condition('name', $contentType)
250
            ->execute();
251
252
        return empty($result) ? '' : reset($result);
253
    }
254
}
255