Completed
Branch CASC/base (fc1e8e)
by
unknown
20:14 queued 01:00
created

ExecuteBatchDeletion::create_job()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 1
dl 0
loc 30
rs 9.1288
c 0
b 0
f 0
1
<?php
2
3
namespace EventEspressoBatchRequest\JobHandlers;
4
5
use EE_Registry;
6
use EEM_Event;
7
use EEM_Price;
8
use EEM_Ticket;
9
use EventEspresso\core\exceptions\InvalidClassException;
10
use EventEspresso\core\exceptions\UnexpectedEntityException;
11
use EventEspresso\core\services\orm\tree_traversal\ModelObjNode;
12
use EventEspressoBatchRequest\Helpers\BatchRequestException;
13
use EventEspressoBatchRequest\Helpers\JobParameters;
14
use EventEspressoBatchRequest\Helpers\JobStepResponse;
15
use EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandler;
16
17
/**
18
 * Class EventDeletion
19
 *
20
 * Given a job code (eg generated by PreviewEventDeletion), performs the deletion of the indicated items.
21
 *
22
 * @package     Event Espresso
23
 * @author         Mike Nelson
24
 * @since         $VID:$
25
 *
26
 */
27
class ExecuteBatchDeletion extends JobHandler
28
{
29
30
31
    /**
32
     *
33
     * @param JobParameters $job_parameters
34
     * @throws BatchRequestException
35
     * @return JobStepResponse
36
     */
37
    public function create_job(JobParameters $job_parameters)
38
    {
39
        $deletion_job_code = $job_parameters->request_datum('deletion_job_code', null);
40
        $roots = get_option('ee_deletion_'  . $deletion_job_code, null);
41
        if ($roots === null) {
42
            throw new UnexpectedEntityException($roots, 'array', esc_html__('The job seems to be stale. Please press the back button in your browser twice.', 'event_espresso'));
43
        }
44
        $models_and_ids_to_delete = [];
45
        foreach ($roots as $root) {
46
            if (! $root instanceof ModelObjNode) {
47
                throw new UnexpectedEntityException($root, 'ModelObjNode');
48
            }
49
            $models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
50
        }
51
        $job_parameters->set_extra_data(
52
            [
53
                'models_and_ids_to_delete' => $models_and_ids_to_delete
54
            ]
55
        );
56
        // Find the job's actual size.
57
        $job_size = 0;
58
        foreach ($models_and_ids_to_delete as $model_name => $ids) {
59
            $job_size += count($ids);
60
        }
61
        $job_parameters->set_job_size($job_size);
62
        return new JobStepResponse(
63
            $job_parameters,
64
            esc_html__('Beginning to delete items...', 'event_espresso')
65
        );
66
    }
67
68
    /**
69
     * Performs another step of the job
70
     * @param JobParameters $job_parameters
71
     * @param int $batch_size
72
     * @return JobStepResponse
73
     * @throws BatchRequestException
74
     */
75
    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
76
    {
77
        // We already have the items IDs. So deleting is really fast. Let's speed it up.
78
        $batch_size *= 10;
79
        $units_processed = 0;
80
        $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
81
        // Build a new list of everything leftover after this request's of deletions.
82
        $models_and_ids_remaining = [];
83
        foreach ($models_and_ids_to_delete as $model_name => $ids_to_delete) {
0 ignored issues
show
Bug introduced by
The expression $models_and_ids_to_delete of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
84
            if ($units_processed < $batch_size) {
85
                $model = EE_Registry::instance()->load_model($model_name);
86
                $ids_to_delete_this_query = array_slice($ids_to_delete, 0, $batch_size - $units_processed, true);
87
                if ($model->has_primary_key_field()) {
88
                    $where_conditions = [
89
                        $model->primary_key_name() => [
90
                            'IN',
91
                            $ids_to_delete_this_query
92
                        ]
93
                    ];
94
                } else {
95
                    $where_conditions = [
96
                        'OR' => []
97
                    ];
98
                    foreach ($ids_to_delete_this_query as $index_primary_key_string) {
99
                        $keys_n_values = $model->parse_index_primary_key_string($index_primary_key_string);
100
                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
101
                    }
102
                }
103
                // Deleting time!
104
                // The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
105
                // two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
106
                $model->delete_permanently(
107
                    [
108
                        $where_conditions
109
                    ],
110
                    false
111
                );
112
                $units_processed += count($ids_to_delete_this_query);
113
                $remaining_ids = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
114
                // If there's any more from this model, we'll do them next time.
115
                if (count($remaining_ids) > 0) {
116
                    $models_and_ids_remaining[ $model_name ] = $remaining_ids;
117
                }
118
            } else {
119
                $models_and_ids_remaining[ $model_name ] = $models_and_ids_to_delete[ $model_name ];
120
            }
121
        }
122
        $job_parameters->mark_processed($units_processed);
123
        // All done deleting for this request. Is there anything to do next time?
124
        if (empty($models_and_ids_remaining)) {
125
            $job_parameters->set_status(JobParameters::status_complete);
126
            return new JobStepResponse(
127
                $job_parameters,
128
                esc_html__('Deletion complete.', 'event_espresso')
129
            );
130
        }
131
        $job_parameters->add_extra_data('models_and_ids_to_delete', $models_and_ids_remaining);
132
        return new JobStepResponse(
133
            $job_parameters,
134
            sprintf(
135
                esc_html__('Deleted %d items.', 'event_espresso'),
136
                $units_processed
137
            )
138
        );
139
    }
140
141
    /**
142
     * Performs any clean-up logic when we know the job is completed
143
     * @param JobParameters $job_parameters
144
     * @return JobStepResponse
145
     * @throws BatchRequestException
146
     */
147
    public function cleanup_job(JobParameters $job_parameters)
148
    {
149
        delete_option(
150
            'EEBatchDeletion' . $job_parameters->request_datum('deletion_job_code')
151
        );
152
    }
153
}
154
// End of file EventDeletion.php
155
// Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
156