Completed
Push — master ( c7d231...71a057 )
by
unknown
06:32 queued 02:07
created

Core::delete_post()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 15
ccs 10
cts 11
cp 0.9091
crap 3.0067
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace KMM\Flattable;
4
5
class Core
6
{
7
    private $plugin_dir;
8
9 6
    public function __construct()
10
    {
11
        global $wpdb;
12 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...
13 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

13
        $this->plugin_dir = /** @scrutinizer ignore-call */ plugin_dir_url(__FILE__) . '../';
Loading history...
14 6
        $this->add_filters();
15
    }
16
17 6
    private function add_filters()
18
    {
19 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

19
        /** @scrutinizer ignore-call */ 
20
        add_action('save_post', [$this, 'save_post'], 100, 3);
Loading history...
20 6
        add_action('delete_post', [$this, 'delete_post'], 100, 3);
21
22 6
        add_action('krn_flattable_check_table', [$this, 'checkTable'], 10, 2);
23 6
        add_action('krn_flattable_publish', [$this, 'manualPublish'], 10);
24
25 6
        add_action('init', [$this, 'init'], 30);
26
27
        //DEMO
28
    }
29
30
    public function init()
31
    {
32
        $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

32
        $post_types = /** @scrutinizer ignore-call */ get_post_types();
Loading history...
33
        foreach ($post_types as $type) {
34
            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

34
            /** @scrutinizer ignore-call */ 
35
            add_action('rest_insert_' . $type, [$this, 'rest_update'], 10, 3);
Loading history...
35
        }
36
    }
37
38 1
    public function rest_update($postObj, $request, $update)
39
    {
40
        /*
41
        * class-wp-rest-attachments-controller.php calls the action with $attachment as array, and also calls parent::update_item(),
42
        *  -> parent class is class-wp-rest-posts-controller.php, that also calls the action, but with $attachment as type WP_Post
43
        */
44 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...
45 1
            return;
46
        }
47
        $_POST['post_type'] = $postObj->post_type;
48
        // save all the data in an anonymous function
49
        $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

49
        $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

49
        $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...
50
            // call the internal save_post after all postmeta is written
51
            $this->save_post($postObj->ID, $postObj, $update);
52
53
            return $response;
54
        };
55
        // add a filter => after all callbacks are called (after update_additional_fields_for_object())
56
        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

56
        /** @scrutinizer ignore-call */ 
57
        add_filter('rest_request_after_callbacks', $trigger_func, 10, 3);
Loading history...
57
    }
58
59
    public function manualPublish($postId)
60
    {
61
        $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
        $_POST['post_type'] = $postObj->post_type;
63
        $this->save_post($postId, $postObj, true);
64
    }
65
66 2
    public function delete_post($postId, $state = false)
67
    {
68 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

68
        $postObj = /** @scrutinizer ignore-call */ get_post($postId);
Loading history...
69 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postObj->post_type;
70
        //check if flattable is enabled for this post type.
71 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

71
        $enabled = /** @scrutinizer ignore-call */ apply_filters('krn_flattable_enabled_' . $postObj->post_type, $state, $postObj, $postObj);
Loading history...
72 2
        if ($enabled) {
73 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

73
            /** @scrutinizer ignore-call */ 
74
            do_action('krn_flattable_pre_delete_' . $postObj->post_type, $postObj);
Loading history...
74 1
            $customCols = apply_filters('krn_flattable_columns_' . $postObj->post_type, [], $postObj);
75
            //check if there are any other than required columns, we dont need an "empty" table
76 1
            if (empty($customCols)) {
77
                return;
78
            }
79 1
            $sql = 'delete from ' . $table_name . ' where post_id=' . $postId;
80 1
            $this->wpdb->query($sql);
81
        }
82
    }
83
84 5
    public function save_post($postId, $postObject, $update, $state = false)
85
    {
86 5
        $postType = false;
87 5
        if (! $postObject) {
88
            //postObject not set, check if $_POST has post_type
89 1
            if (isset($_POST['post_type'])) {
90 1
                $postType = $_POST['post_type'];
91
            }
92
        } else {
93
            //PostObject set
94 4
            $postType = $postObject->post_type;
95
        }
96
        //Neither $postObject nor $_POST[post_type] set return here.
97 5
        if (! $postType) {
98 1
            return;
99
        }
100
101 4
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
102
        //check if flattable is enabled for this post type.
103 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

103
        $enabled = /** @scrutinizer ignore-call */ apply_filters('krn_flattable_enabled_' . $postType, $state, $postObject, $postObject);
Loading history...
104 4
        if ($enabled) {
105
            //We are in flattable enabled mode.
106
            //get a list of columns.
107
            $defaultCols = [
108 1
                ['column' => 'post_id', 'type' => 'int(12)'],
109
                ['column' => 'post_type', 'type' => 'varchar(100)'],
110
            ];
111 1
            $customCols = apply_filters('krn_flattable_columns_' . $postType, [], $postObject);
112 1
            $columns = array_merge($defaultCols, $customCols);
113 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

113
            /** @scrutinizer ignore-call */ 
114
            do_action('krn_flattable_pre_write_' . $postType, $columns, $postObject);
Loading history...
114
            //check if there are any other than required columns, we dont need an "empty" table
115 1
            if (empty($customCols)) {
116
                return;
117
            }
118
            //check if table exists, and if table has atleast required columns
119 1
            if ($this->checkTable($postType, $columns)) {
120 1
                $db_cols = [];
121 1
                $assoc_db = [];
122 1
                foreach ($columns as $column) {
123 1
                    $db_cols[] = $column['column'];
124 1
                    $assoc_db[$column['column']] = $column;
125
                }
126
127 1
                $finalFields = apply_filters('krn_flattable_values_' . $postType, [], $postObject);
128
129 1
                $checkRow = $this->wpdb->get_row("select post_id from $table_name where post_id=" . $postId);
130
                //if we have already a published record, update it
131 1
                $update = true;
132 1
                if (! $checkRow) {
133 1
                    $update = false;
134
                }
135
136 1
                if (! $update) {
137
                    //INSERT
138 1
                    $updateCols = ['post_type', 'post_id'];
139 1
                    $updateVals = ["'" . $postType . "'", $postId];
140 1
                    $updateInserValues = [];
141 1
                    foreach ($finalFields as $key => $value) {
142 1
                        $updateCols[] = $key;
143 1
                        $updateVals[] = $assoc_db[$key]['printf'];
144 1
                        $updateInserValues[] = $value;
145
                    }
146 1
                    $sql = " insert into $table_name (" . join(',', $updateCols) . ') VALUES(' . join(',', $updateVals) . ')';
147 1
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateInserValues));
148 1
                    $this->wpdb->query($query);
149
                } else {
150
                    //UPDATE
151
152
                    //$v = get_field('field_58512668ff1d2', $postId);
153
                    //echo "<pre>";
154
                    //var_dump($v);
155
                    //exit;
156
                    $updateCols = [];
157
                    $updateVals = [];
158
                    foreach ($finalFields as $key => $value) {
159
                        $updateCols[] = $key . ' = ' . $assoc_db[$key]['printf'];
160
                        $updateVals[] = $value;
161
                    }
162
                    $updateVals[] = $postId;
163
164
                    $sql = "update $table_name SET " . join(',', $updateCols) . ' WHERE post_id = %d';
165
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateVals));
166
                    $this->wpdb->query($query);
167
                }
168
169 1
                do_action('krn_flattable_post_write_' . $postType, $postObject);
170
            }
171
        }
172
    }
173
174 2
    public function checkTable($postType, $columns)
175
    {
176 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
177
178 2
        $charset_collate = $this->wpdb->get_charset_collate();
179
180 2
        $sql_columns = [];
181 2
        foreach ($columns as $column) {
182 2
            $sql_columns[] = $column['column'] . ' ' . $column['type'];
183
        }
184
185 2
        $column_string = join(',', $sql_columns);
186
187 2
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
188
            id int(12) NOT NULL AUTO_INCREMENT,
189 2
            $column_string
190
            ,PRIMARY KEY (id)
191 2
        ) $charset_collate;";
192
193 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...
194 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

194
        $a = /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
195
196
        //Check columns
197 2
        foreach ($columns as $column) {
198 2
            $row = $this->wpdb->get_results("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
199 2
                WHERE table_name = '$table_name' AND column_name = '" . $column['column'] . "'");
200
201 2
            if (empty($row)) {
202 2
                $this->wpdb->suppress_errors(true);
203 2
                $this->wpdb->query("ALTER TABLE $table_name ADD " . $column['column'] . ' ' . $column['type']);
204 2
                $this->wpdb->suppress_errors(false);
205
            }
206
        }
207
208 2
        return true;
209
    }
210
}
211