Completed
Branch CASC/base (ee050b)
by
unknown
17:20 queued 09:04
created

PreviewEventDeletion::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
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\services\loaders\LoaderFactory;
10
use EventEspresso\core\services\orm\tree_traversal\ModelObjNode;
11
use EventEspresso\core\services\orm\tree_traversal\NodeGroupDao;
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 list of event IDs, identified all the dependent model objects that would need to be deleted in order to not
21
 * leave any orphaned data.
22
 *
23
 * @package     Event Espresso
24
 * @author         Mike Nelson
25
 * @since         $VID:$
26
 *
27
 */
28
class PreviewEventDeletion extends JobHandler
29
{
30
31
    /**
32
     * @var NodeGroupDao
33
     */
34
    protected $model_obj_node_group_persister;
35
    public function __construct(NodeGroupDao $model_obj_node_group_persister)
36
    {
37
        $this->model_obj_node_group_persister = $model_obj_node_group_persister;
38
    }
39
40
    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
41
    /**
42
     *
43
     * @param JobParameters $job_parameters
44
     * @throws BatchRequestException
45
     * @return JobStepResponse
46
     */
47
    public function create_job(JobParameters $job_parameters)
48
    {
49
        // Set the "root" model objects we will want to delete (record their ID and model)
50
        $event_ids = $job_parameters->request_datum('EVT_IDs', array());
51
        // Find all the root nodes to delete (this isn't just events, because there's other data, like related tickets,
52
        // prices, message templates, etc, whose model definition doesn't make them dependent on events. But,
53
        // we have no UI to access them independent of events, so they may as well get deleted too.)
54
        $model_objects_to_delete = [];
55
        foreach ($event_ids as $event_id) {
0 ignored issues
show
Bug introduced by
The expression $event_ids 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...
56
            $event = EEM_Event::instance()->get_one_by_ID($event_id);
57
            // Also, we want to delete their related, non-global, tickets, prices and message templates
58
            $related_non_global_tickets = EEM_Ticket::instance()->get_all_deleted_and_undeleted(
59
                [
60
                    [
61
                        'TKT_is_default' => false,
62
                        'Datetime.EVT_ID' => $event_id
63
                    ]
64
                ]
65
            );
66
            $related_non_global_prices = EEM_Price::instance()->get_all_deleted_and_undeleted(
67
                [
68
                    [
69
                        'PRC_is_default' => false,
70
                        'Ticket.Datetime.EVT_ID' => $event_id
71
                    ]
72
                ]
73
            );
74
            $model_objects_to_delete = array_merge(
75
                $model_objects_to_delete,
76
                [$event],
77
                $related_non_global_tickets,
78
                $related_non_global_prices
79
            );
80
        }
81
        $roots = [];
82
        foreach ($model_objects_to_delete as $model_object) {
83
            $roots[] = new ModelObjNode($model_object->ID(), $model_object->get_model());
84
        }
85
        $job_parameters->add_extra_data('roots', $roots);
86
        // Set an estimate of how long this will take (we're discovering as we go, so it seems impossible to give
87
        // an accurate count.)
88
        $estimated_work_per_model_obj = 100;
89
        $job_parameters->set_job_size(count($roots) * $estimated_work_per_model_obj);
90
        return new JobStepResponse(
91
            $job_parameters,
92
            esc_html__('Generating preview of data to be deleted...', 'event_espresso')
93
        );
94
    }
95
96
    /**
97
     * Performs another step of the job
98
     * @param JobParameters $job_parameters
99
     * @param int $batch_size
100
     * @return JobStepResponse
101
     * @throws BatchRequestException
102
     */
103
    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
104
    {
105
        // Serializing and unserializing is what really makes this drag on (eg on localhost, the ajax requests took
106
        // about 4 seconds when the batch size was 250, but 3 seconds when the batch size was 50. So like
107
        // 50% of the request is just serializing and unserializing.) So, make the batches much bigger.
108
        $batch_size *= 3;
109
        $units_processed = 0;
110
        foreach ($job_parameters->extra_datum('roots', array()) as $root_node) {
0 ignored issues
show
Bug introduced by
The expression $job_parameters->extra_datum('roots', array()) 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...
111
            if ($units_processed >= $batch_size) {
112
                break;
113
            }
114
            if (! $root_node instanceof ModelObjNode) {
115
                throw new InvalidClassException('ModelObjNode');
116
            }
117
            if ($root_node->isComplete()) {
118
                continue;
119
            }
120
            $units_processed += $root_node->visit($batch_size - $units_processed);
121
        }
122
        $job_parameters->mark_processed($units_processed);
123
        // If the most-recently processed root node is complete, we must be all done because we're doing them
124
        // sequentially.
125
        if (isset($root_node) && $root_node instanceof ModelObjNode && $root_node->isComplete()) {
126
            $job_parameters->set_status(JobParameters::status_complete);
127
            // Show a full progress bar.
128
            $job_parameters->set_units_processed($job_parameters->job_size());
129
            $deletion_job_code = $job_parameters->request_datum('deletion_job_code');
130
            $this->model_obj_node_group_persister->persistModelObjNodesGroup(
131
                $job_parameters->extra_datum('roots'),
132
                $deletion_job_code
133
            );
134
            return new JobStepResponse(
135
                $job_parameters,
136
                esc_html__('Finished identifying items for deletion.', 'event_espresso'),
137
                [
138
                    'deletion_job_code' => $deletion_job_code
139
                ]
140
            );
141
        } else {
142
            // Because the job size was a guess, it may have likely been provden wrong. We don't want to show more work
143
            // done than we originally said there would be. So adjust the estimate.
144
            if (($job_parameters->units_processed() / $job_parameters->job_size()) > .8) {
145
                $job_parameters->set_job_size($job_parameters->job_size() * 2);
146
            }
147
            return new JobStepResponse(
148
                $job_parameters,
149
                sprintf(
150
                    esc_html__('Identified %d items for deletion.', 'event_espresso'),
151
                    $units_processed
152
                )
153
            );
154
        }
155
    }
156
157
    /**
158
     * Performs any clean-up logic when we know the job is completed
159
     * @param JobParameters $job_parameters
160
     * @return JobStepResponse
161
     */
162
    public function cleanup_job(JobParameters $job_parameters)
163
    {
164
        // Nothing much to do. We can't delete the option with the built tree because we may need it in a moment for the deletion
165
        return new JobStepResponse(
166
            $job_parameters,
167
            esc_html__('All done', 'event_espresso')
168
        );
169
    }
170
}
171
// End of file EventDeletion.php
172
// Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
173