Completed
Branch CASC/batch-deletion (24fd65)
by
unknown
17:02 queued 09:01
created

ExecuteBatchDeletion::continue_job()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 58

Duplication

Lines 16
Ratio 27.59 %

Importance

Changes 0
Metric Value
cc 7
nc 11
nop 2
dl 16
loc 58
rs 7.983
c 0
b 0
f 0

How to fix   Long Method   

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 EventEspressoBatchRequest\JobHandlers;
4
5
use EEM_Event;
6
use EEM_Price;
7
use EEM_Ticket;
8
use EventEspresso\core\exceptions\InvalidClassException;
9
use EventEspresso\core\exceptions\UnexpectedEntityException;
10
use EventEspresso\core\services\orm\tree_traversal\ModelObjNode;
11
use EventEspressoBatchRequest\Helpers\BatchRequestException;
12
use EventEspressoBatchRequest\Helpers\JobParameters;
13
use EventEspressoBatchRequest\Helpers\JobStepResponse;
14
use EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandler;
15
16
/**
17
 * Class EventDeletion
18
 *
19
 * Given a job code (eg generated by PreviewEventDeletion), performs the deletion of the indicated items.
20
 *
21
 * @package     Event Espresso
22
 * @author         Mike Nelson
23
 * @since         $VID:$
24
 *
25
 */
26
class ExecuteBatchDeletion extends JobHandler
27
{
28
29
30
    /**
31
     *
32
     * @param JobParameters $job_parameters
33
     * @throws BatchRequestException
34
     * @return JobStepResponse
35
     */
36
    public function create_job(JobParameters $job_parameters)
37
    {
38
        $deletion_job_code = $job_parameters->request_datum('deletion_job_code', array());
39
        $roots = get_option('EEBatchDeletion'  . $deletion_job_code, null);
40
        if($roots === null){
41
            throw new UnexpectedEntityException($roots, 'array', esc_html__('The job seems to be stale. Please press the back button in your browser twice.', 'event_espresso'));
42
        }
43
        $ids_to_delete = [];
44
        foreach ($roots as $root) {
45
            if(! $root instanceof ModelObjNode){
46
                throw new UnexpectedEntityException($root, 'ModelObjNode');
47
            }
48
            $ids_to_delete = array_replace_recursive($ids_to_delete, $root->getIds());
49
        }
50
        $job_parameters->set_extra_data(
51
            [
52
                'deletion_job_code' => $deletion_job_code,
53
                'ids_to_delete' => $ids_to_delete
54
            ]
55
        );
56
        // Find the job's actual size.
57
        $job_size = 0;
58
        foreach($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
        $units_processed = 0;
78
        $ids_to_delete = $job_parameters->extra_datum('ids_to_delete', []);
79
        $ids_remaining = [];
80
        foreach($ids_to_delete as $model_name => $ids){
0 ignored issues
show
Bug introduced by
The expression $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...
81
            if($units_processed < $batch_size){
82
                $model = EE_Registry::instance()->load_model($model_name);
83
                $ids_to_delete_this_query = array_slice($ids, 0, $batch_size, true);
84 View Code Duplication
                if ($model->has_primary_key_field()) {
85
                    $where_conditions = [
86
                        $model->primary_key_name() => [
87
                            'IN',
88
                            $ids
89
                        ]
90
                    ];
91
                } else {
92
                    $where_conditions = [
93
                        'OR' => []
94
                    ];
95
                    foreach ($ids as $index_primary_key_string) {
96
                        $keys_n_values = $model->parse_index_primary_key_string($index_primary_key_string);
97
                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
98
                    }
99
                }
100
                $deletion_count = $model->delete_permanently(
101
                    [
102
                        $where_conditions
103
                    ],
104
                    false
105
                );
106
                $units_processed += $deletion_count;
107
                $remaining_ids = array_diff_key($ids, $ids_to_delete_this_query);
108
                // If there's any more from this model, we'll do them next time.
109
                if(count($remaining_ids) > 0){
110
                    $ids_remaining[$model_name] = $remaining_ids;
111
                }
112
            } else {
113
                $ids_remaining[$model_name] = $ids_to_delete[$model_name];
114
            }
115
            $job_parameters->mark_processed($units_processed);
116
            if(empty($ids_remaining)){
117
                $job_parameters->set_status(JobParameters::status_complete);
118
                return new JobStepResponse(
119
                    $job_parameters,
120
                    esc_html__('Deletion complete.', 'event_espresso')
121
                );
122
            }
123
            $job_parameters->add_extra_data('ids_to_delete', $ids_remaining);
124
            return new JobStepResponse(
125
                $job_parameters,
126
                sprintf(
127
                    esc_html__('Deleted %d items.', 'event_espresso'),
128
                    $units_processed
129
                )
130
            );
131
        }
132
    }
133
134
    /**
135
     * Performs any clean-up logic when we know the job is completed
136
     * @param JobParameters $job_parameters
137
     * @return JobStepResponse
138
     * @throws BatchRequestException
139
     */
140
    public function cleanup_job(JobParameters $job_parameters)
141
    {
142
        delete_option(
143
            'EEBatchDeletion' . $job_parameters->extra_datum('deletion_job_code')
144
        );
145
    }
146
}
147
// End of file EventDeletion.php
148
// Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
149