Core::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
namespace KMM\Flattable;
4
5
class Core {
6
    private $plugin_dir;
7
8 6
    public function __construct() {
9
        global $wpdb;
10 6
        $this->wpdb = $wpdb;
0 ignored issues
show
Bug Best Practice introduced by
The property wpdb does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
11 6
        $this->plugin_dir = plugin_dir_url(__FILE__) . '../';
0 ignored issues
show
Bug introduced by
The function plugin_dir_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

11
        $this->plugin_dir = /** @scrutinizer ignore-call */ plugin_dir_url(__FILE__) . '../';
Loading history...
12 6
        $this->add_filters();
13
    }
14
15 6
    private function add_filters() {
16 6
        add_action('save_post', [$this, 'save_post'], 100, 3);
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

16
        /** @scrutinizer ignore-call */ 
17
        add_action('save_post', [$this, 'save_post'], 100, 3);
Loading history...
17 6
        add_action('delete_post', [$this, 'delete_post'], 100, 3);
18
19 6
        add_action('krn_flattable_check_table', [$this, 'checkTable'], 10, 2);
20 6
        add_action('krn_flattable_publish', [$this, 'manualPublish'], 10);
21
22 6
        add_action('init', [$this, 'init'], 30);
23
24
        //DEMO
25
    }
26
27
    public function init() {
28
        $post_types = get_post_types();
0 ignored issues
show
Bug introduced by
The function get_post_types was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

28
        $post_types = /** @scrutinizer ignore-call */ get_post_types();
Loading history...
29
        foreach ($post_types as $type) {
30
            add_action('rest_insert_' . $type, [$this, 'rest_update'], 10, 3);
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

30
            /** @scrutinizer ignore-call */ 
31
            add_action('rest_insert_' . $type, [$this, 'rest_update'], 10, 3);
Loading history...
31
        }
32
    }
33
34 1
    public function rest_update($postObj, $request, $update) {
35
        /*
36
        * class-wp-rest-attachments-controller.php calls the action with $attachment as array, and also calls parent::update_item(),
37
        *  -> parent class is class-wp-rest-posts-controller.php, that also calls the action, but with $attachment as type WP_Post
38
        */
39 1
        if (! $postObj instanceof \WP_Post) {
0 ignored issues
show
Bug introduced by
The type WP_Post was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40 1
            return;
41
        }
42
        $_POST['post_type'] = $postObj->post_type;
43
        // save all the data in an anonymous function
44
        $trigger_func = function ($response, $handler, $request) use ($postObj, $update) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

44
        $trigger_func = function ($response, $handler, /** @scrutinizer ignore-unused */ $request) use ($postObj, $update) {

This check looks for 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 $handler is not used and could be removed. ( Ignorable by Annotation )

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

44
        $trigger_func = function ($response, /** @scrutinizer ignore-unused */ $handler, $request) use ($postObj, $update) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
45
            // call the internal save_post after all postmeta is written
46
            $this->save_post($postObj->ID, $postObj, $update);
47
48
            return $response;
49
        };
50
        // add a filter => after all callbacks are called (after update_additional_fields_for_object())
51
        add_filter('rest_request_after_callbacks', $trigger_func, 10, 3);
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

51
        /** @scrutinizer ignore-call */ 
52
        add_filter('rest_request_after_callbacks', $trigger_func, 10, 3);
Loading history...
52
    }
53
54
    public function manualPublish($postId) {
55
        $postObj = get_post($postId);
0 ignored issues
show
Bug introduced by
The function get_post was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

55
        $postObj = /** @scrutinizer ignore-call */ get_post($postId);
Loading history...
56
        $_POST['post_type'] = $postObj->post_type;
57
        $this->save_post($postId, $postObj, true);
58
    }
59
60 2
    public function delete_post($postId, $state = false) {
61 2
        $postObj = get_post($postId);
0 ignored issues
show
Bug introduced by
The function get_post was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

61
        $postObj = /** @scrutinizer ignore-call */ get_post($postId);
Loading history...
62 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postObj->post_type;
63
        //check if flattable is enabled for this post type.
64 2
        $enabled = apply_filters('krn_flattable_enabled_' . $postObj->post_type, $state, $postObj, $postObj);
0 ignored issues
show
Bug introduced by
The function apply_filters was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

64
        $enabled = /** @scrutinizer ignore-call */ apply_filters('krn_flattable_enabled_' . $postObj->post_type, $state, $postObj, $postObj);
Loading history...
65 2
        if ($enabled) {
66 1
            do_action('krn_flattable_pre_delete_' . $postObj->post_type, $postObj);
0 ignored issues
show
Bug introduced by
The function do_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

66
            /** @scrutinizer ignore-call */ 
67
            do_action('krn_flattable_pre_delete_' . $postObj->post_type, $postObj);
Loading history...
67 1
            $customCols = apply_filters('krn_flattable_columns_' . $postObj->post_type, [], $postObj);
68
            //check if there are any other than required columns, we dont need an "empty" table
69 1
            if (empty($customCols)) {
70
                return;
71
            }
72 1
            $sql = 'delete from ' . $table_name . ' where post_id=' . $postId;
73 1
            $this->wpdb->query($sql);
74
        }
75
    }
76
77 5
    public function save_post($postId, $postObject, $update, $state = false) {
78 5
        $postType = false;
79 5
        if (! $postObject) {
80
            //postObject not set, check if $_POST has post_type
81 1
            if (isset($_POST['post_type'])) {
82 1
                $postType = $_POST['post_type'];
83
            }
84
        } else {
85
            //PostObject set
86 4
            $postType = $postObject->post_type;
87
        }
88
        //Neither $postObject nor $_POST[post_type] set return here.
89 5
        if (! $postType) {
90 1
            return;
91
        }
92
93 4
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
94
        //check if flattable is enabled for this post type.
95 4
        $enabled = apply_filters('krn_flattable_enabled_' . $postType, $state, $postObject, $postObject);
0 ignored issues
show
Bug introduced by
The function apply_filters was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

95
        $enabled = /** @scrutinizer ignore-call */ apply_filters('krn_flattable_enabled_' . $postType, $state, $postObject, $postObject);
Loading history...
96 4
        if ($enabled) {
97
            //We are in flattable enabled mode.
98
            //get a list of columns.
99
            $defaultCols = [
100 1
                ['column' => 'post_id', 'type' => 'int(12)'],
101
                ['column' => 'post_type', 'type' => 'varchar(100)'],
102
            ];
103 1
            $customCols = apply_filters('krn_flattable_columns_' . $postType, [], $postObject);
104 1
            $columns = array_merge($defaultCols, $customCols);
105 1
            do_action('krn_flattable_pre_write_' . $postType, $columns, $postObject);
0 ignored issues
show
Bug introduced by
The function do_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

105
            /** @scrutinizer ignore-call */ 
106
            do_action('krn_flattable_pre_write_' . $postType, $columns, $postObject);
Loading history...
106
            //check if there are any other than required columns, we dont need an "empty" table
107 1
            if (empty($customCols)) {
108
                return;
109
            }
110
            //check if table exists, and if table has atleast required columns
111 1
            if ($this->checkTable($postType, $columns)) {
112 1
                $db_cols = [];
113 1
                $assoc_db = [];
114 1
                foreach ($columns as $column) {
115 1
                    $db_cols[] = $column['column'];
116 1
                    $assoc_db[$column['column']] = $column;
117
                }
118
119 1
                $finalFields = apply_filters('krn_flattable_values_' . $postType, [], $postObject);
120
121 1
                $checkRow = $this->wpdb->get_row("select post_id from $table_name where post_id=" . $postId);
122
                //if we have already a published record, update it
123 1
                $update = true;
124 1
                if (! $checkRow) {
125 1
                    $update = false;
126
                }
127
128 1
                if (! $update) {
129
                    //INSERT
130 1
                    $updateCols = ['post_type', 'post_id'];
131 1
                    $updateVals = ["'" . $postType . "'", $postId];
132 1
                    $updateInserValues = [];
133 1
                    foreach ($finalFields as $key => $value) {
134 1
                        $updateCols[] = '`' . $key . '`';
135 1
                        $updateVals[] = $assoc_db[$key]['printf'];
136 1
                        $updateInserValues[] = $value;
137
                    }
138 1
                    $sql = " insert into $table_name (" . join(',', $updateCols) . ') VALUES(' . join(',', $updateVals) . ')';
139 1
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateInserValues));
140 1
                    $this->wpdb->query($query);
141
                } else {
142
                    //UPDATE
143
144
                    //$v = get_field('field_58512668ff1d2', $postId);
145
                    //echo "<pre>";
146
                    //var_dump($v);
147
                    //exit;
148
                    $updateCols = [];
149
                    $updateVals = [];
150
                    foreach ($finalFields as $key => $value) {
151
                        $updateCols[] = '`' . $key . '`' . ' = ' . $assoc_db[$key]['printf'];
152
                        $updateVals[] = $value;
153
                    }
154
                    $updateVals[] = $postId;
155
156
                    $sql = "update $table_name SET " . join(',', $updateCols) . ' WHERE post_id = %d';
157
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateVals));
158
                    $this->wpdb->query($query);
159
                }
160
161 1
                do_action('krn_flattable_post_write_' . $postType, $postObject);
162
            }
163
        }
164
    }
165
166 2
    public function checkTable($postType, $columns) {
167 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
168
169 2
        $charset_collate = $this->wpdb->get_charset_collate();
170
171 2
        $is_hit = false;
172 2
        $cache_key = sha1($table_name) . '-' . sha1(json_encode($columns));
173 2
        wp_cache_get($cache_key, 'flattable', false, $is_hit);
0 ignored issues
show
Bug introduced by
The function wp_cache_get was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

173
        /** @scrutinizer ignore-call */ 
174
        wp_cache_get($cache_key, 'flattable', false, $is_hit);
Loading history...
174 2
        if ($is_hit) {
0 ignored issues
show
introduced by
The condition $is_hit is always false.
Loading history...
175
            return true;
176
        }
177
178 2
        $sql_columns = [];
179 2
        foreach ($columns as $column) {
180 2
            $sql_columns[] = '`' . $column['column'] . '`' . ' ' . $column['type'];
181
        }
182
183 2
        $column_string = join(',', $sql_columns);
184
185 2
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
186
            id int(12) NOT NULL AUTO_INCREMENT,
187 2
            $column_string
188
            ,PRIMARY KEY (id)
189 2
        ) $charset_collate;";
190
191 2
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
0 ignored issues
show
Bug introduced by
The constant KMM\Flattable\ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
192 2
        $a = dbDelta($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $a is dead and can be removed.
Loading history...
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

192
        $a = /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
193
194
        //Check columns
195 2
        foreach ($columns as $column) {
196 2
            $row = $this->wpdb->get_results("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
197 2
                WHERE table_name = '$table_name' AND column_name = '" . $column['column'] . "'");
198
199 2
            if (empty($row)) {
200 2
                if ((! defined('WP_DEBUG') || ! WP_DEBUG) || defined('KRN_IS_TESTING')) {
0 ignored issues
show
Bug introduced by
The constant KMM\Flattable\WP_DEBUG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
201 2
                    $this->wpdb->suppress_errors(true);
202
                }
203 2
                $this->wpdb->query("ALTER TABLE $table_name ADD `" . $column['column'] . '` ' . $column['type']);
204 2
                $this->wpdb->suppress_errors(false);
205
            }
206
        }
207 2
        wp_cache_set($cache_key, 'SET', 'flattable');
0 ignored issues
show
Bug introduced by
The function wp_cache_set was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

207
        /** @scrutinizer ignore-call */ 
208
        wp_cache_set($cache_key, 'SET', 'flattable');
Loading history...
208
209 2
        return true;
210
    }
211
}
212