Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Passed
Push — datatable-single-component ( 863f17...49cc78 )
by Pedro
13:04
created

Datatable::applyCachedConfig()   C

Complexity

Conditions 13
Paths 27

Size

Total Lines 71
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 46
nc 27
nop 1
dl 0
loc 71
rs 6.6166
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Backpack\CRUD\app\Library\Datatable;
4
5
use Backpack\CRUD\app\Library\CrudPanel\CrudPanel;
6
use Backpack\CRUD\CrudManager;
7
use Illuminate\Support\Facades\Cache;
8
use Illuminate\Support\Str;
9
use Illuminate\View\Component;
10
11
class Datatable extends Component
12
{
13
    protected string $tableId;
14
15
    public function __construct(
16
        private string $controller,
17
        private ?CrudPanel $crud = null,
18
        private bool $updatesUrl = true,
19
        private ?\Closure $configure = null,
20
        private ?string $type = null,
21
        private ?string $name = null
22
    ) {
23
        // Set active controller for proper context
24
        CrudManager::setActiveController($controller);
0 ignored issues
show
Bug introduced by
The method setActiveController() does not exist on Backpack\CRUD\CrudManager. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

24
        CrudManager::/** @scrutinizer ignore-call */ 
25
                     setActiveController($controller);
Loading history...
25
        
26
        $this->crud ??= CrudManager::crudFromController($controller);
0 ignored issues
show
Bug introduced by
The method crudFromController() does not exist on Backpack\CRUD\CrudManager. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

26
        $this->crud ??= CrudManager::/** @scrutinizer ignore-call */ crudFromController($controller);
Loading history...
27
       
28
        $controllerPart = str_replace('\\', '_', $this->controller);
29
        $typePart = $this->type ?? 'default';
30
        $namePart = $this->name ?? 'default';
31
        $uniqueId = md5($controllerPart . '_' . $typePart . '_' . $namePart);
32
        $this->tableId = 'crudTable_' . $uniqueId;
33
        
34
        
35
        if ($this->configure) {
36
            // Apply the configuration
37
            ($this->configure)($this->crud);
38
            
39
            // Store the configuration in cache for Ajax requests
40
            $this->storeDatatableConfig();
41
        }
42
        
43
        if (! $this->crud->getOperationSetting('datatablesUrl')) {
0 ignored issues
show
Bug introduced by
The method getOperationSetting() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

43
        if (! $this->crud->/** @scrutinizer ignore-call */ getOperationSetting('datatablesUrl')) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
44
            $this->crud->setOperationSetting('datatablesUrl', $this->crud->getRoute());
45
        }
46
        
47
        // Reset the active controller
48
        CrudManager::unsetActiveController($controller);
0 ignored issues
show
Bug introduced by
The method unsetActiveController() does not exist on Backpack\CRUD\CrudManager. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

48
        CrudManager::/** @scrutinizer ignore-call */ 
49
                     unsetActiveController($controller);
Loading history...
49
    }
50
    
51
    /**
52
     * Store the datatable configuration in the cache for later use in Ajax requests
53
     */
54
    private function storeDatatableConfig()
55
    {
56
        if (!$this->configure) {
57
            return;
58
        }
59
    
60
        $controllerClass = $this->controller;
61
        $cruds = CrudManager::getCruds();
0 ignored issues
show
Bug introduced by
The method getCruds() does not exist on Backpack\CRUD\CrudManager. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
        /** @scrutinizer ignore-call */ 
62
        $cruds = CrudManager::getCruds();
Loading history...
62
        $parentCrud = reset($cruds);
63
        
64
        if ($parentCrud && $parentCrud->getCurrentEntry()) {
65
            $parentEntry = $parentCrud->getCurrentEntry();
66
            $parentController = $parentCrud->crudController;
67
            $cacheKey = 'datatable_config_' . $this->tableId;
68
            
69
            // Store the controller class, parent entry, element type and name
70
            Cache::put($cacheKey, [
71
                'controller' => $controllerClass,
72
                'parentController' => $parentController,
73
                'parent_entry' => $parentEntry,
74
                'element_type' => $this->type,
75
                'element_name' => $this->name,
76
            ], now()->addHours(1));
77
            
78
            $this->crud->setOperationSetting('datatable_id', $this->tableId);
79
        }
80
    }
81
    
82
    public static function applyCachedConfig($crud)
83
    {
84
        $tableId = request('datatable_id');
85
        
86
        if (!$tableId) {
87
            \Log::debug('Missing datatable_id in request parameters');
88
            return false;
89
        }
90
        
91
        $cacheKey = 'datatable_config_' . $tableId;
92
        $cachedData = Cache::get($cacheKey);
93
        
94
        if (!$cachedData) {
95
            \Log::debug('No cached configuration found for the given datatable_id');
96
            return false;
97
        }
98
        
99
        try {            
100
            \Log::debug('Found matching configuration by table ID', [
101
                'controller' => $cachedData['controller'],
102
                'element_type' => $cachedData['element_type'],
103
                'element_name' => $cachedData['element_name'],
104
                'table_id' => $tableId
105
            ]);
106
            
107
            // Get the parent crud instance
108
            $parentCrud = CrudManager::crudFromController($cachedData['parentController'], 'show');
109
            $entry = $cachedData['parent_entry'];
110
            
111
            // Get element type and name from cached data
112
            $elementType = $cachedData['element_type'];
113
            $elementName = $cachedData['element_name'];
114
            
115
            \Log::debug('Element type and name', [
116
                'element_type' => $elementType,
117
                'element_name' => $elementName
118
            ]);
119
            
120
            if ($elementType === 'column') {
121
                $column = $parentCrud->columns()[$elementName] ?? null;
122
                if ($column && isset($column['configure'])) {
123
                    self::applyColumnDatatableConfig($parentCrud, $crud, $elementName, $entry);
124
                    // clear the cache after applying the configuration
125
                    Cache::forget($cacheKey);
126
                    return true;
127
                }
128
                \Log::debug('Column not found or no configure closure defined');
129
                return false;
130
            } else if ($elementType === 'widget') {
131
                $widgets = $parentCrud->getOperationSetting('widgets') ?? [];
132
                foreach ($widgets as $widget) {
133
                    if ($widget['type'] === 'datatable' && 
134
                        (isset($widget['name']) && $widget['name'] === $elementName) && 
135
                        isset($widget['configure'])) {
136
                        self::applyWidgetDatatableConfig($parentCrud, $crud, $elementName, $entry);
137
                        // clear the cache after applying the configuration
138
                        Cache::forget($cacheKey);
139
                        return true;
140
                    }
141
                }
142
                \Log::debug('Widget not found or no configure closure defined');
143
                return false;
144
            }
145
        } catch (\Exception $e) {
146
            \Log::error("Error applying cached datatable config: " . $e->getMessage(), [
147
                'exception' => $e
148
            ]);
149
        }
150
        
151
        \Log::debug('No matching configuration found');
152
        return false;
153
    }
154
155
    private static function applyColumnDatatableConfig($parentCrud, $crud, $elementName, $entry)
156
    {
157
        $column = $parentCrud->columns()[$elementName];
158
        if (isset($column['configure'])) {
159
            ($column['configure'])($crud, $entry);
160
            return true;
161
        }
162
        return false;
163
    }
164
165
    private static function applyWidgetDatatableConfig($parentCrud, $crud, $elementName, $entry)
166
    {
167
        $widgets = $parentCrud->getOperationSetting('widgets') ?? [];
168
        foreach ($widgets as $widget) {
169
            if ($widget['type'] === 'datatable' && 
170
                (isset($widget['name']) && $widget['name'] === $elementName) && 
171
                isset($widget['configure'])) {
172
                ($widget['configure'])($crud, $entry);
173
                return true;
174
            }
175
        }
176
        return false;
177
    }
178
179
    public function render()
180
    {
181
        return view('crud::datatable.datatable', [
182
            'crud' => $this->crud,
183
            'updatesUrl' => $this->updatesUrl,
184
            'tableId' => $this->tableId,
185
        ]);
186
    }
187
}