Completed
Push — master ( a682ae...89ebe6 )
by Welling
07:42
created

ClientLocal::createFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Directus – <http://getdirectus.com>
5
 *
6
 * @link      The canonical repository – <https://github.com/directus/directus>
7
 * @copyright Copyright 2006-2016 RANGER Studio, LLC – <http://rangerstudio.com>
8
 * @license   GNU General Public License (v3) – <http://www.gnu.org/copyleft/gpl.html>
9
 */
10
11
namespace Directus\SDK;
12
13
use Directus\Database\Connection;
14
use Directus\Database\TableGateway\BaseTableGateway;
15
use Directus\Database\TableGateway\DirectusActivityTableGateway;
16
use Directus\Database\TableGateway\DirectusMessagesTableGateway;
17
use Directus\Database\TableGateway\DirectusPreferencesTableGateway;
18
use Directus\Database\TableGateway\DirectusPrivilegesTableGateway;
19
use Directus\Database\TableGateway\DirectusSettingsTableGateway;
20
use Directus\Database\TableGateway\DirectusUiTableGateway;
21
use Directus\Database\TableGateway\DirectusUsersTableGateway;
22
use Directus\Database\TableGateway\RelationalTableGateway;
23
use Directus\Database\TableSchema;
24
use Directus\Util\ArrayUtils;
25
use Directus\Util\SchemaUtils;
26
use Directus\Util\StringUtils;
27
use Zend\Db\Sql\Predicate\In;
28
29
/**
30
 * Client Local
31
 *
32
 * Client to Interact with the database directly using Directus Database Component
33
 *
34
 * @author Welling Guzmán <[email protected]>
35
 */
36
class ClientLocal extends AbstractClient
37
{
38
    /**
39
     * @var BaseTableGateway[]
40
     */
41
    protected $tableGateways = [];
42
43
    /**
44
     * @var Connection
45
     */
46
    protected $connection = null;
47
48
    /**
49
     * ClientLocal constructor.
50
     *
51
     * @param $connection
52
     */
53
    public function __construct($connection)
54
    {
55
        $this->connection = $connection;
56
    }
57
58
    /**
59
     * @inheritDoc
60
     */
61
    public function getTables(array $params = [])
62
    {
63
        return $this->createResponseFromData(TableSchema::getTablesSchema($params));
64
    }
65
66
    /**
67
     * @inheritDoc
68
     */
69
    public function getTable($tableName)
70
    {
71
        return $this->createResponseFromData(TableSchema::getSchemaArray($tableName));
72
    }
73
74
    /**
75
     * @inheritDoc
76
     */
77
    public function getColumns($tableName, array $params = [])
78
    {
79
        return $this->createResponseFromData(TableSchema::getColumnSchemaArray($tableName, $params));
0 ignored issues
show
Bug introduced by
The method getColumnSchemaArray() does not exist on Directus\Database\TableSchema. Did you maybe mean getColumnSchema()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
80
    }
81
82
    /**
83
     * @inheritDoc
84
     */
85
    public function getColumn($tableName, $columnName)
86
    {
87
        return $this->createResponseFromData(TableSchema::getColumnSchema($tableName, $columnName)->toArray());
88
    }
89
90
    /**
91
     * @inheritDoc
92
     */
93
    public function getItems($tableName, array $params = [])
94
    {
95
        $tableGateway = $this->getTableGateway($tableName);
96
97
        return $this->createResponseFromData($tableGateway->getItems($params));
98
    }
99
100
    /**
101
     * @inheritDoc
102
     */
103
    public function getItem($tableName, $id, array $params = [])
104
    {
105
        // @TODO: Dynamic ID
106
        return $this->getItems($tableName, array_merge($params, [
107
            'id' => $id
108
        ]));
109
    }
110
111
    /**
112
     * @inheritDoc
113
     */
114
    public function getUsers(array $params = [])
115
    {
116
        // @TODO: store the directus tables somewhere (SchemaManager?)
117
        return $this->getItems('directus_users', $params);
118
    }
119
120
    /**
121
     * @inheritDoc
122
     */
123
    public function getUser($id, array $params = [])
124
    {
125
        return $this->getItem('directus_users', $id, $params);
126
    }
127
128
    /**
129
     * @inheritDoc
130
     */
131
    public function getGroups(array $params = [])
132
    {
133
        return $this->getItems('directus_groups', $params);
134
    }
135
136
    /**
137
     * @inheritDoc
138
     */
139
    public function getGroup($id, array $params = [])
140
    {
141
        return $this->getItem('directus_groups', $id, $params);
142
    }
143
144
    /**
145
     * @inheritDoc
146
     */
147
    public function getGroupPrivileges($groupID)
148
    {
149
        $this->getItems('directus_privileges', [
150
            'filter' => [
151
                'group_id' => ['eq' => $groupID]
152
            ]
153
        ]);
154
    }
155
156
    /**
157
     * @inheritDoc
158
     */
159
    public function getFiles(array $params = [])
160
    {
161
        return $this->getItems('directus_files', $params);
162
    }
163
164
    /**
165
     * @inheritDoc
166
     */
167
    public function getFile($id, array $params = [])
168
    {
169
        return $this->getItem('directus_files', $id, $params);
170
    }
171
172
    /**
173
     * @inheritDoc
174
     */
175
    public function getSettings()
176
    {
177
        return $this->getItems('directus_settings');
178
    }
179
180
    /**
181
     * @inheritDoc
182
     */
183 View Code Duplication
    public function getSettingsByCollection($collectionName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
184
    {
185
        $connection = $this->container->get('connection');
186
        $acl = $this->container->get('acl');
187
        $tableGateway = new DirectusSettingsTableGateway($connection, $acl);
188
189
        $data = [
190
            'meta' => [
191
                'table' => 'directus_settings',
192
                'type' => 'entry',
193
                'settings_collection' => $collectionName
194
            ],
195
            'data' => $tableGateway->fetchCollection($collectionName)
196
        ];
197
198
        return $this->createResponseFromData($data);
199
    }
200
201
    /**
202
     * @inheritdoc
203
     */
204
    public function updateSettings($collection, array $data)
205
    {
206
        $connection = $this->container->get('connection');
207
        $acl = $this->container->get('acl');
208
        $tableGateway = new DirectusSettingsTableGateway($connection, $acl);
209
210
        $tableGateway->setValues($collection, $data);
211
212
        return $this->getSettingsByCollection($collection);
213
    }
214
215
    /**
216
     * @inheritDoc
217
     */
218 View Code Duplication
    public function getMessages($userId = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219
    {
220
        $connection = $this->container->get('connection');
221
        $acl = $this->container->get('acl');
222
223
        if ($userId === null) {
224
            $userId = $acl->getUserId();
225
        }
226
227
        $messagesTableGateway = new DirectusMessagesTableGateway($connection, $acl);
228
        $result = $messagesTableGateway->fetchMessagesInboxWithHeaders($userId);
229
230
        return $this->createResponseFromData($result);
231
    }
232
233 View Code Duplication
    public function getMessage($id, $userId = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
    {
235
        $connection = $this->container->get('connection');
236
        $acl = $this->container->get('acl');
237
238
        if ($userId === null) {
239
            $userId = $acl->getUserId();
240
        }
241
242
        $messagesTableGateway = new DirectusMessagesTableGateway($connection, $acl);
243
        $message = $messagesTableGateway->fetchMessageWithRecipients($id, $userId);
244
245
        return $this->createResponseFromData($message);
246
    }
247
248
    /**
249
     * @inheritDoc
250
     */
251 View Code Duplication
    public function createItem($tableName, array $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
252
    {
253
        $tableGateway = $this->getTableGateway($tableName);
254
        $data = $this->processData($tableName, $data);
255
256
        foreach($data as $key => $value) {
257
            if ($value instanceof File) {
258
                $data[$key] = $this->processFile($value);
259
            }
260
        }
261
262
        $newRecord = $tableGateway->manageRecordUpdate($tableName, $data);
263
264
        return $this->getItem($tableName, $newRecord[$tableGateway->primaryKeyFieldName]);
265
    }
266
267
    /**
268
     * @inheritDoc
269
     */
270 View Code Duplication
    public function updateItem($tableName, $id, array $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
271
    {
272
        $tableGateway = $this->getTableGateway($tableName);
273
        $data = $this->processData($tableName, $data);
274
275
        foreach($data as $key => $value) {
276
            if ($value instanceof File) {
277
                $data[$key] = $this->processFile($value);
278
            }
279
        }
280
281
        $updatedRecord = $tableGateway->manageRecordUpdate($tableName, array_merge($data, ['id' => $id]));
282
283
        return $this->getItem($tableName, $updatedRecord[$tableGateway->primaryKeyFieldName]);
284
    }
285
286
    /**
287
     * @inheritDoc
288
     */
289
    public function deleteItem($tableName, $ids, $hard = false)
290
    {
291
        // @TODO: Accept EntryCollection and Entry
292
        $tableGateway = $this->getTableGateway($tableName);
293
294
        if (!is_array($ids)) {
295
            $ids = [$ids];
296
        }
297
298
        if ($hard === true) {
299
            return $tableGateway->delete(function($delete) use ($ids) {
300
                return $delete->where->in('id', $ids);
301
            });
302
        }
303
304
        return $tableGateway->update(['active' => 0], new In('id', $ids));
0 ignored issues
show
Documentation introduced by
new \Zend\Db\Sql\Predicate\In('id', $ids) is of type object<Zend\Db\Sql\Predicate\In>, but the function expects a string|array|object<Closure>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
305
    }
306
307
    /**
308
     * @inheritDoc
309
     */
310
    public function createUser(array $data)
311
    {
312
        return $this->createItem('directus_users', $data);
313
    }
314
315
    /**
316
     * @inheritDoc
317
     */
318
    public function updateUser($id, array $data)
319
    {
320
        return $this->updateItem('directus_users', $id, $data);
321
    }
322
323
    /**
324
     * @inheritDoc
325
     */
326
    public function deleteUser($ids, $hard = false)
327
    {
328
        return $this->deleteItem('directus_users', $ids, $hard);
329
    }
330
331
    /**
332
     * @inheritDoc
333
     */
334
    public function createFile(File $file)
335
    {
336
        $data = $this->processFile($file);
337
338
        return $this->createItem('directus_files', $data);
339
    }
340
341
    /**
342
     * @inheritDoc
343
     */
344
    public function updateFile($id, $data)
345
    {
346
        if ($data instanceof File) {
347
            $data = $this->processFile($data);
348
        }
349
350
        return $this->updateItem('directus_files', $id, $data);
351
    }
352
353
    /**
354
     * @inheritDoc
355
     */
356
    public function deleteFile($ids, $hard = false)
357
    {
358
        return $this->deleteItem('directus_files', $ids, $hard);
359
    }
360
361
    public function createPreferences($data)
362
    {
363
        if (!ArrayUtils::contains($data, ['title', 'table_name'])) {
364
            throw new \Exception('title and table_name are required');
365
        }
366
367
        $acl = $this->container->get('acl');
368
        $data['user'] = $acl->getUserId();
369
370
        return $this->createItem('directus_preferences', $data);
371
    }
372
373
    /**
374
     * @inheritdoc
375
     */
376
    public function createBookmark($data)
377
    {
378
        $acl = $this->container->get('acl');
379
        $data['user'] = $acl->getUserId();
380
381
        $preferences = $this->createPreferences(ArrayUtils::pick($data, [
382
            'title', 'table_name', 'sort', 'status', 'search_string', 'sort_order', 'columns_visible', 'user'
383
        ]));
384
385
        $title = $preferences->title;
0 ignored issues
show
Bug introduced by
The property title does not seem to exist in Directus\SDK\Response\EntryCollection.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
386
        $tableName = $preferences->table_name;
0 ignored issues
show
Bug introduced by
The property table_name does not seem to exist in Directus\SDK\Response\EntryCollection.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
387
        $bookmarkData = [
388
            'section' => 'search',
389
            'title' => $title,
390
            'url' => 'tables/' . $tableName . '/pref/' . $title,
391
            'user' => $data['user']
392
        ];
393
394
        return $this->createItem('directus_bookmarks', $bookmarkData);
395
    }
396
397
    /**
398
     * @inheritdoc
399
     */
400
    public function getBookmark($id)
401
    {
402
        return $this->getItem('directus_bookmarks', $id);
403
    }
404
405
    /**
406
     * @inheritdoc
407
     */
408
    public function getBookmarks($userId = null)
409
    {
410
        $filters = [];
411
        if ($userId !== null) {
412
            $filters = [
413
                'filters' => ['user' => ['eq' => $userId]]
414
            ];
415
        }
416
417
        return $this->getItems('directus_bookmarks', $filters);
418
    }
419
420
    /**
421
     * @inheritdoc
422
     */
423
    public function createColumn($data)
424
    {
425
        $data = $this->parseColumnData($data);
426
427
        $tableGateway = $this->getTableGateway($data['table_name']);
428
429
        $tableGateway->addColumn($data['table_name'], ArrayUtils::omit($data, ['table_name']));
430
431
        return $this->getColumn($data['table_name'], $data['column_name']);
432
    }
433
434
    /**
435
     * @inheritdoc
436
     */
437
    public function createGroup(array $data)
438
    {
439
        return $this->createItem('directus_groups', $data);
440
    }
441
442
    /**
443
     * @inheritdoc
444
     */
445
    public function createMessage(array $data)
446
    {
447
        $this->requiredAttributes(['from', 'message', 'subject'], $data);
448
        $this->requiredOneAttribute(['to', 'toGroup'], $data);
449
450
        $recipients = $this->getMessagesTo($data);
451
        $recipients = explode(',', $recipients);
452
        ArrayUtils::remove($data, ['to', 'toGroup']);
453
454
        $groupRecipients = [];
455
        $userRecipients = [];
456
        foreach ($recipients as $recipient) {
457
            $typeAndId = explode('_', $recipient);
458
            if ($typeAndId[0] == 0) {
459
                $userRecipients[] = $typeAndId[1];
460
            } else {
461
                $groupRecipients[] = $typeAndId[1];
462
            }
463
        }
464
465
        $ZendDb = $this->container->get('connection');
0 ignored issues
show
Coding Style introduced by
$ZendDb does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
466
        $acl = $this->container->get('acl');
467
        if (count($groupRecipients) > 0) {
468
            $usersTableGateway = new DirectusUsersTableGateway($ZendDb, $acl);
0 ignored issues
show
Coding Style introduced by
$ZendDb does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
469
            $result = $usersTableGateway->findActiveUserIdsByGroupIds($groupRecipients);
470
            foreach ($result as $item) {
471
                $userRecipients[] = $item['id'];
472
            }
473
        }
474
475
        $userRecipients[] = $acl->getUserId();
476
477
        $messagesTableGateway = new DirectusMessagesTableGateway($ZendDb, $acl);
0 ignored issues
show
Coding Style introduced by
$ZendDb does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
478
        $id = $messagesTableGateway->sendMessage($data, array_unique($userRecipients), $acl->getUserId());
479
480
        if ($id) {
481
            $Activity = new DirectusActivityTableGateway($ZendDb, $acl);
0 ignored issues
show
Coding Style introduced by
$Activity does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
482
            $data['id'] = $id;
483
            $Activity->recordMessage($data, $acl->getUserId());
0 ignored issues
show
Coding Style introduced by
$Activity does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
484
        }
485
486
        $message = $messagesTableGateway->fetchMessageWithRecipients($id, $acl->getUserId());
487
        $response = [
488
            'meta' => [
489
                'type' => 'item',
490
                'table' => 'directus_messages'
491
            ],
492
            'data' => $message
493
        ];
494
495
        return $this->createResponseFromData($response);
496
    }
497
498
    /**
499
     * @inheritdoc
500
     */
501
    public function sendMessage(array $data)
502
    {
503
        return $this->createMessage($data);
504
    }
505
506 View Code Duplication
    public function createPrivileges(array $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
507
    {
508
        $connection = $this->container->get('connection');
509
        $acl = $this->container->get('acl');
510
        $privileges = new DirectusPrivilegesTableGateway($connection, $acl);
511
512
        $response = [
513
            'meta' => [
514
                'type' => 'item',
515
                'table' => 'directus_privileges'
516
            ],
517
            'data' => $privileges->insertPrivilege($data)
518
        ];
519
520
        return $this->createResponseFromData($response);
521
    }
522
523
    public function createTable($name, array $data = [])
524
    {
525
        $isTableNameAlphanumeric = preg_match("/[a-z0-9]+/i", $name);
526
        $zeroOrMoreUnderscoresDashes = preg_match("/[_-]*/i", $name);
527
528
        if (!($isTableNameAlphanumeric && $zeroOrMoreUnderscoresDashes)) {
529
            return $this->createResponseFromData(['error' => ['message' => 'invalid_table_name']]);
530
        }
531
532
        $schema = $this->container->get('schemaManager');
533
        $emitter = $this->container->get('emitter');
534
        if (!$schema->tableExists($name)) {
535
            $emitter->run('table.create:before', $name);
536
            // Through API:
537
            // Remove spaces and symbols from table name
538
            // And in lowercase
539
            $name = SchemaUtils::cleanTableName($name);
540
            $schema->createTable($name);
541
            $emitter->run('table.create', $name);
542
            $emitter->run('table.create:after', $name);
543
        }
544
545
        $connection = $this->container->get('connection');
546
        $acl = $this->container->get('acl');
547
        $privileges = new DirectusPrivilegesTableGateway($connection, $acl);
548
549
        return $this->createResponseFromData($privileges->insertPrivilege([
550
            'group_id' => 1,
551
            'table_name' => $name
552
        ]));
553
    }
554
555
    /**
556
     * @inheritdoc
557
     */
558
    public function createColumnUIOptions(array $data)
559
    {
560
        $this->requiredAttributes(['table', 'column', 'ui', 'options'], $data);
561
        $tableGateway = $this->getTableGateway('directus_ui');
562
563
        $table = $data['table'];
564
        $column = $data['column'];
565
        $ui = $data['ui'];
566
567
        $data = $data['options'];
568
        $keys = ['table_name' => $table, 'column_name' => $column, 'ui_name' => $ui];
569
        $uis = to_name_value($data, $keys);
570
571
        $column_settings = [];
0 ignored issues
show
Coding Style introduced by
$column_settings does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
572
        foreach ($uis as $col) {
573
            $existing = $tableGateway->select(['table_name' => $table, 'column_name' => $column, 'ui_name' => $ui, 'name' => $col['name']])->toArray();
574
            if (count($existing) > 0) {
575
                $col['id'] = $existing[0]['id'];
576
            }
577
            array_push($column_settings, $col);
0 ignored issues
show
Coding Style introduced by
$column_settings does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
578
        }
579
        $tableGateway->updateCollection($column_settings);
0 ignored issues
show
Coding Style introduced by
$column_settings does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
580
581
        $connection = $this->container->get('connection');
582
        $acl = $this->container->get('acl');
583
        $UiOptions = new DirectusUiTableGateway($connection, $acl);
0 ignored issues
show
Coding Style introduced by
$UiOptions does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
584
        $response = $UiOptions->fetchOptions($table, $column, $ui);
0 ignored issues
show
Coding Style introduced by
$UiOptions does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
585
586
        if (!$response) {
587
            $response = [
588
                'error' => [
589
                    'message' => sprintf('unable_to_find_column_%s_options_for_%s', ['column' => $column, 'ui' => $ui])
590
                ],
591
                'success' => false
592
            ];
593
        } else {
594
            $response = [
595
                'meta' => [
596
                    'type' => 'item',
597
                    'table' => 'directus_ui'
598
                ],
599
                'data' => $response
600
            ];
601
        }
602
603
        return $this->createResponseFromData($response);
604
    }
605
606 View Code Duplication
    public function getPreferences($table, $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
607
    {
608
        $acl = $this->container->get('acl');
609
        $connection = $this->container->get('connection');
610
        $preferencesTableGateway = new DirectusPreferencesTableGateway($connection, $acl);
611
612
        $response = [
613
            'meta' => [
614
                'type' => 'item',
615
                'table' => 'directus_preferences'
616
            ],
617
            'data' => $preferencesTableGateway->fetchByUserAndTableAndTitle($user, $table)
618
        ];
619
620
        return $this->createResponseFromData($response);
621
    }
622
623
    /**
624
     * @inheritdoc
625
     */
626
    public function deleteBookmark($id, $hard = false)
627
    {
628
        return $this->deleteItem('directus_bookmarks', $id, $hard);
629
    }
630
631
    /**
632
     * @inheritdoc
633
     */
634 View Code Duplication
    public function deleteColumn($name, $table)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
635
    {
636
        $tableGateway = $this->getTableGateway($table);
637
        $success = $tableGateway->dropColumn($name);
638
639
        $response = [
640
            'success' => (bool) $success
641
        ];
642
643
        if (!$success) {
644
            $response['error'] = [
645
                'message' => sprintf('unable_to_remove_column_%s', ['column_name' => $name])
646
            ];
647
        }
648
649
        return $this->createResponseFromData($response);
650
    }
651
652
    /**
653
     * @inheritdoc
654
     */
655
    public function deleteGroup($id, $hard = false)
656
    {
657
        return $this->deleteItem('directus_groups', $id, $hard);
658
    }
659
660
    /**
661
     * @inheritdoc
662
     */
663 View Code Duplication
    public function deleteTable($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
664
    {
665
        $tableGateway = $this->getTableGateway($name);
666
        $success = $tableGateway->drop();
667
668
        $response = [
669
            'success' => (bool) $success
670
        ];
671
672
        if (!$success) {
673
            $response['error'] = [
674
                'message' => sprintf('unable_to_remove_table_%s', ['table_name' => $name])
675
            ];
676
        }
677
678
        return $this->createResponseFromData($response);
679
    }
680
681
    public function getActivity(array $params = [])
682
    {
683
        $connection = $this->container->get('connection');
684
        $acl = $this->container->get('acl');
685
        $tableGateway = new DirectusActivityTableGateway($connection, $acl);
686
687
        $data = $tableGateway->fetchFeed($params);
688
689
        return $this->createResponseFromData($data);
690
    }
691
692
    /**
693
     * @inheritdoc
694
     */
695
    public function getRandom(array $options = [])
696
    {
697
        $length = (int) ArrayUtils::get($options, 'length', 32);
698
699
        return $this->createResponseFromData([
700
            'success' => true,
701
            'data' => [
702
                'random' => StringUtils::randomString($length)
703
            ]
704
        ]);
705
    }
706
707
    /**
708
     * @inheritdoc
709
     */
710
    public function getHash($string, array $options = [])
711
    {
712
        $hashManager = $this->container->get('hashManager');
713
714
        try {
715
            $hash = $hashManager->hash($string, $options);
716
            $data = [
717
                'success' => true,
718
                'data' => [
719
                    'hash' => $hash
720
                ]
721
            ];
722
        } catch (\Exception $e) {
723
            $data = [
724
                'success' => false,
725
                'error' => [
726
                    'message' => $e->getMessage()
727
                ]
728
            ];
729
        }
730
731
        return $this->createResponseFromData($data);
732
    }
733
734
    /**
735
     * Get a table gateway for the given table name
736
     *
737
     * @param $tableName
738
     *
739
     * @return RelationalTableGateway
740
     */
741
    protected function getTableGateway($tableName)
742
    {
743
        if (!array_key_exists($tableName, $this->tableGateways)) {
744
            $acl = TableSchema::getAclInstance();
745
            $this->tableGateways[$tableName] = new RelationalTableGateway($tableName, $this->connection, $acl);
746
        }
747
748
        return $this->tableGateways[$tableName];
749
    }
750
}
751