Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like QueuedJobService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use QueuedJobService, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
24 | class QueuedJobService { |
||
|
|||
25 | /** |
||
26 | * @var int |
||
27 | */ |
||
28 | private static $stall_threshold = 3; |
||
29 | |||
30 | /** |
||
31 | * How much ram will we allow before pausing and releasing the memory? |
||
32 | * |
||
33 | * For instance, set to 134217728 (128MB) to pause this process if used memory exceeds |
||
34 | * this value. This needs to be set to a value lower than the php_ini max_memory as |
||
35 | * the system will otherwise crash before shutdown can be handled gracefully. |
||
36 | * |
||
37 | * @var int |
||
38 | * @config |
||
39 | */ |
||
40 | private static $memory_limit = 134217728; |
||
41 | |||
42 | /** |
||
43 | * Optional time limit (in seconds) to run the service before restarting to release resources. |
||
44 | * |
||
45 | * Defaults to no limit. |
||
46 | * |
||
47 | * @var int |
||
48 | * @config |
||
49 | */ |
||
50 | private static $time_limit = 0; |
||
51 | |||
52 | /** |
||
53 | * Timestamp (in seconds) when the queue was started |
||
54 | * |
||
55 | * @var int |
||
56 | */ |
||
57 | protected $startedAt = 0; |
||
58 | |||
59 | /** |
||
60 | * Should "immediate" jobs be managed using the shutdown function? |
||
61 | * |
||
62 | * It is recommended you set up an inotify watch and use that for |
||
63 | * triggering immediate jobs. See the wiki for more information |
||
64 | * |
||
65 | * @var boolean |
||
66 | */ |
||
67 | private static $use_shutdown_function = true; |
||
68 | |||
69 | /** |
||
70 | * The location for immediate jobs to be stored in |
||
71 | * |
||
72 | * @var string |
||
73 | */ |
||
74 | private static $cache_dir = 'queuedjobs'; |
||
75 | |||
76 | /** |
||
77 | * @var DefaultQueueHandler |
||
78 | */ |
||
79 | public $queueHandler; |
||
80 | |||
81 | /** |
||
82 | * |
||
83 | * @var TaskRunnerEngine |
||
84 | */ |
||
85 | public $queueRunner; |
||
86 | |||
87 | /** |
||
88 | * Config controlled list of default/required jobs |
||
89 | * @var Array |
||
90 | */ |
||
91 | public $defaultJobs; |
||
92 | |||
93 | /** |
||
94 | * Register our shutdown handler |
||
95 | */ |
||
96 | public function __construct() { |
||
110 | |||
111 | /** |
||
112 | * Adds a job to the queue to be started |
||
113 | * |
||
114 | * Relevant data about the job will be persisted using a QueuedJobDescriptor |
||
115 | * |
||
116 | * @param QueuedJob $job |
||
117 | * The job to start. |
||
118 | * @param $startAfter |
||
119 | * The date (in Y-m-d H:i:s format) to start execution after |
||
120 | * @param int $userId |
||
121 | * The ID of a user to execute the job as. Defaults to the current user |
||
122 | * @return int |
||
123 | */ |
||
124 | public function queueJob(QueuedJob $job, $startAfter = null, $userId = null, $queueName = null) { |
||
161 | |||
162 | /** |
||
163 | * Start a job (or however the queue handler determines it should be started) |
||
164 | * |
||
165 | * @param JobDescriptor $jobDescriptor |
||
166 | * @param date $startAfter |
||
167 | */ |
||
168 | public function startJob($jobDescriptor, $startAfter = null) { |
||
176 | |||
177 | /** |
||
178 | * Copies data from a job into a descriptor for persisting |
||
179 | * |
||
180 | * @param QueuedJob $job |
||
181 | * @param JobDescriptor $jobDescriptor |
||
182 | */ |
||
183 | protected function copyJobToDescriptor($job, $jobDescriptor) { |
||
196 | |||
197 | /** |
||
198 | * @param QueuedJobDescriptor $jobDescriptor |
||
199 | * @param QueuedJob $job |
||
200 | */ |
||
201 | protected function copyDescriptorToJob($jobDescriptor, $job) { |
||
228 | |||
229 | /** |
||
230 | * Check the current job queues and see if any of the jobs currently in there should be started. If so, |
||
231 | * return the next job that should be executed |
||
232 | * |
||
233 | * @param string $type Job type |
||
234 | * @return QueuedJobDescriptor |
||
235 | */ |
||
236 | public function getNextPendingJob($type = null) { |
||
271 | |||
272 | /** |
||
273 | * Runs an explicit check on all currently running jobs to make sure their "processed" count is incrementing |
||
274 | * between each run. If it's not, then we need to flag it as paused due to an error. |
||
275 | * |
||
276 | * This typically happens when a PHP fatal error is thrown, which can't be picked up by the error |
||
277 | * handler or exception checker; in this case, we detect these stalled jobs later and fix (try) to |
||
278 | * fix them |
||
279 | * |
||
280 | * @param int $queue The queue to check against |
||
281 | */ |
||
282 | public function checkJobHealth($queue = null) { |
||
322 | |||
323 | /** |
||
324 | * Checks through all the scheduled jobs that are expected to exist |
||
325 | */ |
||
326 | public function checkdefaultJobs($queue = null) { |
||
327 | $queue = $queue ?: QueuedJob::QUEUED; |
||
328 | if (count($this->defaultJobs)) { |
||
329 | |||
330 | $activeJobs = QueuedJobDescriptor::get()->filter(array( |
||
331 | 'JobStatus' => array( |
||
332 | QueuedJob::STATUS_NEW, |
||
333 | QueuedJob::STATUS_INIT, |
||
334 | QueuedJob::STATUS_RUN, |
||
335 | QueuedJob::STATUS_WAIT, |
||
336 | ), |
||
337 | 'JobType' => $queue |
||
338 | )); |
||
339 | |||
340 | foreach ($this->defaultJobs as $title => $jobConfig) { |
||
341 | if (!isset($jobConfig['filter']) || !isset($jobConfig['type'])) { |
||
342 | SS_Log::log("Default Job config: $title incorrectly set up. Please check the readme for examples", SS_Log::ERR); |
||
343 | continue; |
||
344 | } |
||
345 | |||
346 | $job = $activeJobs->filter(array_merge( |
||
347 | array('Implementation' => $jobConfig['type']), $jobConfig['filter'] |
||
348 | )); |
||
349 | |||
350 | if (!$job->count()) { |
||
351 | Email::create() |
||
352 | ->setTo(isset($jobConfig['email']) ? $jobConfig['email'] : Email::config()->admin_email) |
||
353 | ->setSubject('Default Job "' . $title . '" missing') |
||
354 | ->populateTemplate(array('Title' => $title, 'Site' => Director::absoluteBaseURL())) |
||
355 | ->populateTemplate($jobConfig) |
||
356 | ->setTemplate('QueuedJobsDefaultJob') |
||
357 | ->send(); |
||
358 | |||
359 | if (isset($jobConfig['recreate']) && $jobConfig['recreate']) { |
||
360 | if (!isset($jobConfig['construct']) || !isset($jobConfig['startDateFormat']) || !isset($jobConfig['startTimeString'])) { |
||
361 | SS_Log::log("Default Job config: $title incorrectly set up. Please check the readme for examples", SS_Log::ERR); |
||
362 | continue; |
||
363 | } |
||
364 | singleton('QueuedJobService')->queueJob( |
||
365 | Injector::inst()->createWithArgs($jobConfig['type'], $jobConfig['construct']), |
||
366 | date($jobConfig['startDateFormat'], strtotime($jobConfig['startTimeString'])) |
||
367 | ); |
||
368 | } |
||
369 | } |
||
370 | } |
||
371 | } |
||
372 | } |
||
373 | |||
374 | /** |
||
375 | * Attempt to restart a stalled job |
||
376 | * |
||
377 | * @param QueuedJobDescriptor $stalledJob |
||
378 | * @return bool True if the job was successfully restarted |
||
379 | */ |
||
380 | protected function restartStalledJob($stalledJob) { |
||
408 | |||
409 | /** |
||
410 | * Prepares the given jobDescriptor for execution. Returns the job that |
||
411 | * will actually be run in a state ready for executing. |
||
412 | * |
||
413 | * Note that this is called each time a job is picked up to be executed from the cron |
||
414 | * job - meaning that jobs that are paused and restarted will have 'setup()' called on them again, |
||
415 | * so your job MUST detect that and act accordingly. |
||
416 | * |
||
417 | * @param QueuedJobDescriptor $jobDescriptor |
||
418 | * The Job descriptor of a job to prepare for execution |
||
419 | * |
||
420 | * @return QueuedJob|boolean |
||
421 | */ |
||
422 | protected function initialiseJob(QueuedJobDescriptor $jobDescriptor) { |
||
450 | |||
451 | /** |
||
452 | * Given a {@link QueuedJobDescriptor} mark the job as initialised. Works sort of like a mutex. |
||
453 | * Currently a database lock isn't entirely achievable, due to database adapters not supporting locks. |
||
454 | * This may still have a race condition, but this should minimise the possibility. |
||
455 | * Side effect is the job status will be changed to "Initialised". |
||
456 | * |
||
457 | * Assumption is the job has a status of "Queued" or "Wait". |
||
458 | * |
||
459 | * @param QueuedJobDescriptor $jobDescriptor |
||
460 | * @return boolean |
||
461 | */ |
||
462 | protected function grabMutex(QueuedJobDescriptor $jobDescriptor) { |
||
483 | |||
484 | /** |
||
485 | * Start the actual execution of a job. |
||
486 | * The assumption is the jobID refers to a {@link QueuedJobDescriptor} that is status set as "Queued". |
||
487 | * |
||
488 | * This method will continue executing until the job says it's completed |
||
489 | * |
||
490 | * @param int $jobId |
||
491 | * The ID of the job to start executing |
||
492 | * @return boolean |
||
493 | */ |
||
494 | public function runJob($jobId) { |
||
691 | |||
692 | /** |
||
693 | * Start timer |
||
694 | */ |
||
695 | protected function markStarted() { |
||
700 | |||
701 | /** |
||
702 | * Is execution time too long? |
||
703 | * |
||
704 | * @return bool True if the script has passed the configured time_limit |
||
705 | */ |
||
706 | protected function hasPassedTimeLimit() { |
||
720 | |||
721 | /** |
||
722 | * Is memory usage too high? |
||
723 | * |
||
724 | * @return bool |
||
725 | */ |
||
726 | protected function isMemoryTooHigh() { |
||
731 | |||
732 | /** |
||
733 | * Get peak memory usage of this application |
||
734 | * |
||
735 | * @return float |
||
736 | */ |
||
737 | protected function getMemoryUsage() { |
||
742 | |||
743 | /** |
||
744 | * Determines the memory limit (in bytes) for this application |
||
745 | * Limits to the smaller of memory_limit configured via php.ini or silverstripe config |
||
746 | * |
||
747 | * @return float Memory limit in bytes |
||
748 | */ |
||
749 | protected function getMemoryLimit() { |
||
762 | |||
763 | /** |
||
764 | * Calculate the current memory limit of the server |
||
765 | * |
||
766 | * @return float |
||
767 | */ |
||
768 | protected function getPHPMemoryLimit() { |
||
771 | |||
772 | /** |
||
773 | * Convert memory limit string to bytes. |
||
774 | * Based on implementation in install.php5 |
||
775 | * |
||
776 | * @param string $memString |
||
777 | * @return float |
||
778 | */ |
||
779 | protected function parseMemory($memString) { |
||
793 | |||
794 | protected function humanReadable($size) { |
||
798 | |||
799 | |||
800 | /** |
||
801 | * Gets a list of all the current jobs (or jobs that have recently finished) |
||
802 | * |
||
803 | * @param string $type |
||
804 | * if we're after a particular job list |
||
805 | * @param int $includeUpUntil |
||
806 | * The number of seconds to include jobs that have just finished, allowing a job list to be built that |
||
807 | * includes recently finished jobs |
||
808 | */ |
||
809 | public function getJobList($type = null, $includeUpUntil = 0) { |
||
812 | |||
813 | /** |
||
814 | * Return the SQL filter used to get the job list - this is used by the UI for displaying the job list... |
||
815 | * |
||
816 | * @param string $type |
||
817 | * if we're after a particular job list |
||
818 | * @param int $includeUpUntil |
||
819 | * The number of seconds to include jobs that have just finished, allowing a job list to be built that |
||
820 | * includes recently finished jobs |
||
821 | * @return string |
||
822 | */ |
||
823 | public function getJobListFilter($type = null, $includeUpUntil = 0) { |
||
837 | |||
838 | /** |
||
839 | * Process the job queue with the current queue runner |
||
840 | * |
||
841 | * @param string $queue |
||
842 | */ |
||
843 | public function runQueue($queue) { |
||
848 | |||
849 | /** |
||
850 | * Process all jobs from a given queue |
||
851 | * |
||
852 | * @param string $name The job queue to completely process |
||
853 | */ |
||
854 | public function processJobQueue($name) { |
||
887 | |||
888 | /** |
||
889 | * When PHP shuts down, we want to process all of the immediate queue items |
||
890 | * |
||
891 | * We use the 'getNextPendingJob' method, instead of just iterating the queue, to ensure |
||
892 | * we ignore paused or stalled jobs. |
||
893 | */ |
||
894 | public function onShutdown() { |
||
897 | } |
||
898 | |||
934 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.