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 BaseJobManager 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 BaseJobManager, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
17 | abstract class BaseJobManager extends AbstractJobManager |
||
18 | { |
||
19 | /** Number of jobs to prune / reset / gather at a time */ |
||
20 | const FETCH_COUNT = 100; |
||
21 | |||
22 | /** Number of seconds before a job is considered stalled if the runner is no longer active */ |
||
23 | const STALLED_SECONDS = 1800; |
||
24 | protected $objectManager; |
||
25 | protected $objectName; |
||
26 | protected $archiveObjectName; |
||
27 | protected $runClass; |
||
28 | protected $runArchiveClass; |
||
29 | protected static $saveInsertCalled = null; |
||
30 | protected static $resetInsertCalled = null; |
||
31 | |||
32 | /** |
||
33 | * @param string $objectName |
||
34 | * @param string $archiveObjectName |
||
35 | * @param string $runClass |
||
36 | * @param string $runArchiveClass |
||
37 | */ |
||
38 | 3 | public function __construct(ObjectManager $objectManager, |
|
50 | |||
51 | /** |
||
52 | * @return ObjectManager |
||
53 | */ |
||
54 | 22 | public function getObjectManager() |
|
58 | |||
59 | /** |
||
60 | * @return string |
||
61 | */ |
||
62 | 20 | public function getObjectName() |
|
66 | |||
67 | /** |
||
68 | * @return string |
||
69 | */ |
||
70 | 16 | public function getArchiveObjectName() |
|
74 | |||
75 | /** |
||
76 | * @return string |
||
77 | */ |
||
78 | 4 | public function getRunClass() |
|
82 | |||
83 | /** |
||
84 | * @return string |
||
85 | */ |
||
86 | 4 | public function getRunArchiveClass() |
|
90 | |||
91 | /** |
||
92 | * @return ObjectRepository |
||
93 | */ |
||
94 | 16 | public function getRepository() |
|
98 | |||
99 | /** |
||
100 | * @param string $objectName |
||
101 | */ |
||
102 | abstract protected function countJobsByStatus($objectName, $status, $workerName = null, $method = null); |
||
103 | |||
104 | 2 | public function resetErroneousJobs($workerName = null, $method = null) |
|
105 | { |
||
106 | 2 | $count = $this->countJobsByStatus($this->getArchiveObjectName(), Job::STATUS_ERROR, $workerName, $method); |
|
107 | |||
108 | 2 | $criterion = ['status' => Job::STATUS_ERROR]; |
|
109 | 2 | $this->addWorkerNameMethod($criterion, $workerName, $method); |
|
110 | |||
111 | 2 | $countProcessed = 0; |
|
112 | 2 | for ($i = 0; $i < $count; $i += static::FETCH_COUNT) { |
|
113 | 2 | $countProcessed += $this->resetJobsByCriterion( |
|
114 | 2 | $criterion, static::FETCH_COUNT, $i); |
|
115 | } |
||
116 | |||
117 | 2 | return $countProcessed; |
|
118 | } |
||
119 | |||
120 | /** |
||
121 | * Sets the status to Job::STATUS_EXPIRED for those jobs that are expired. |
||
122 | * |
||
123 | * @param null $workerName |
||
124 | * @param null $method |
||
125 | * |
||
126 | * @return mixed |
||
127 | */ |
||
128 | abstract protected function updateExpired($workerName = null, $method = null); |
||
129 | |||
130 | 8 | protected function addWorkerNameMethod(array &$criterion, $workerName = null, $method = null) |
|
131 | { |
||
132 | 8 | if (null !== $workerName) { |
|
133 | 4 | $criterion['workerName'] = $workerName; |
|
134 | } |
||
135 | 8 | if (null !== $method) { |
|
136 | 4 | $criterion['method'] = $method; |
|
137 | } |
||
138 | 8 | } |
|
139 | |||
140 | 2 | public function pruneExpiredJobs($workerName = null, $method = null) |
|
141 | { |
||
142 | 2 | $count = $this->updateExpired($workerName, $method); |
|
143 | 2 | $criterion = ['status' => Job::STATUS_EXPIRED]; |
|
144 | 2 | $this->addWorkerNameMethod($criterion, $workerName, $method); |
|
145 | 2 | $objectManager = $this->getObjectManager(); |
|
146 | 2 | $repository = $this->getRepository(); |
|
147 | 2 | $finalCount = 0; |
|
148 | 2 | for ($i = 0; $i < $count; $i += static::FETCH_COUNT) { |
|
149 | 2 | $expiredJobs = $repository->findBy($criterion, null, static::FETCH_COUNT, $i); |
|
150 | 2 | if (!empty($expiredJobs)) { |
|
151 | 2 | foreach ($expiredJobs as $expiredJob) { |
|
152 | /* @var Job $expiredJob */ |
||
153 | 2 | $expiredJob->setStatus(Job::STATUS_EXPIRED); |
|
154 | 2 | $objectManager->remove($expiredJob); |
|
155 | 2 | ++$finalCount; |
|
156 | } |
||
157 | } |
||
158 | 2 | $objectManager->flush(); |
|
159 | } |
||
160 | |||
161 | 2 | return $finalCount; |
|
162 | } |
||
163 | |||
164 | 4 | protected function getStalledJobs($workerName = null, $method = null) |
|
175 | |||
176 | 4 | protected function findRunningJobs($criterion, $count) |
|
177 | { |
||
178 | 4 | $repository = $this->getRepository(); |
|
179 | 4 | $runningJobsById = []; |
|
180 | |||
181 | 4 | for ($i = 0; $i < $count; $i += static::FETCH_COUNT) { |
|
182 | 4 | $runningJobs = $repository->findBy($criterion, null, static::FETCH_COUNT, $i); |
|
183 | 4 | if (!empty($runningJobs)) { |
|
184 | 4 | foreach ($runningJobs as $job) { |
|
185 | /** @var RetryableJob $job */ |
||
186 | 4 | if (null !== $runId = $job->getRunId()) { |
|
187 | 4 | $runningJobsById[$runId][] = $job; |
|
188 | } |
||
189 | } |
||
190 | } |
||
191 | } |
||
192 | |||
193 | 4 | return $runningJobsById; |
|
194 | } |
||
195 | |||
196 | 4 | protected function extractStalledJobs(array $runningJobsById) |
|
197 | { |
||
198 | 4 | $objectManager = $this->getObjectManager(); |
|
199 | 4 | $runRepository = $objectManager->getRepository($this->runClass); |
|
200 | /** @var EntityRepository|DocumentRepository $runArchiveRepository */ |
||
201 | 4 | $runArchiveRepository = $objectManager->getRepository($this->runArchiveClass); |
|
202 | |||
203 | 4 | $stalledJobs = []; |
|
204 | 4 | foreach (array_keys($runningJobsById) as $runId) { |
|
205 | 4 | if ($runRepository->find($runId)) { |
|
206 | continue; |
||
207 | } |
||
208 | /** @var Run $run */ |
||
209 | 4 | if ($run = $runArchiveRepository->find($runId)) { |
|
210 | 4 | if ($endTime = $run->getEndedAt()) { |
|
211 | // Did it end over an hour ago |
||
212 | 4 | if ((time() - $endTime->getTimestamp()) > static::STALLED_SECONDS) { |
|
213 | 4 | $stalledJobs = array_merge($stalledJobs, $runningJobsById[$runId]); |
|
214 | } |
||
215 | } |
||
216 | } |
||
217 | } |
||
218 | |||
219 | 4 | return $stalledJobs; |
|
220 | } |
||
221 | |||
222 | 2 | public function resetStalledJobs($workerName = null, $method = null) |
|
223 | { |
||
224 | 2 | $stalledJobs = $this->getStalledJobs($workerName, $method); |
|
225 | |||
226 | 2 | $objectManager = $this->getObjectManager(); |
|
227 | |||
228 | 2 | $countProcessed = 0; |
|
229 | 2 | for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) { |
|
230 | 2 | for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) { |
|
231 | 2 | $job = $stalledJobs[$j]; |
|
232 | /* RetryableJob $job */ |
||
233 | 2 | $job->setStalledCount($job->getStalledCount() + 1); |
|
234 | 2 | View Code Duplication | if (null !== ($maxStalled = $job->getMaxStalled()) && $job->getStalledCount() >= $maxStalled) { |
|
|||
235 | $job->setStatus(RetryableJob::STATUS_MAX_STALLED); |
||
236 | $objectManager->remove($job); |
||
237 | continue; |
||
238 | } |
||
239 | 2 | View Code Duplication | if (null !== ($maxRetries = $job->getMaxRetries()) && $job->getRetries() >= $maxRetries) { |
240 | $job->setStatus(RetryableJob::STATUS_MAX_RETRIES); |
||
241 | $objectManager->remove($job); |
||
242 | continue; |
||
243 | } |
||
244 | |||
245 | 2 | $job->setRetries($job->getRetries() + 1); |
|
246 | 2 | $job->setStatus(BaseJob::STATUS_NEW); |
|
247 | 2 | $job->setLocked(null); |
|
248 | 2 | $job->setLockedAt(null); |
|
249 | 2 | $objectManager->persist($job); |
|
250 | 2 | ++$countProcessed; |
|
251 | } |
||
252 | 2 | $objectManager->flush(); |
|
253 | } |
||
254 | |||
255 | 2 | return $countProcessed; |
|
256 | } |
||
257 | |||
258 | /** |
||
259 | * @param string $workerName |
||
260 | * @param string $method |
||
261 | */ |
||
262 | 2 | public function pruneStalledJobs($workerName = null, $method = null) |
|
263 | { |
||
264 | 2 | $stalledJobs = $this->getStalledJobs($workerName, $method); |
|
265 | 2 | $objectManager = $this->getObjectManager(); |
|
266 | |||
267 | 2 | $countProcessed = 0; |
|
268 | 2 | for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) { |
|
269 | 2 | for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) { |
|
270 | /** @var RetryableJob $job */ |
||
271 | 2 | $job = $stalledJobs[$j]; |
|
272 | 2 | $job->setStalledCount($job->getStalledCount() + 1); |
|
273 | 2 | $job->setStatus(BaseJob::STATUS_ERROR); |
|
274 | 2 | $job->setMessage('stalled'); |
|
275 | 2 | View Code Duplication | if (null !== ($maxStalled = $job->getMaxStalled()) && ($job->getStalledCount() >= $job->getMaxStalled())) { |
276 | $job->setStatus(RetryableJob::STATUS_MAX_STALLED); |
||
277 | } |
||
278 | 2 | $objectManager->remove($job); |
|
279 | 2 | ++$countProcessed; |
|
280 | } |
||
281 | 2 | $objectManager->flush(); |
|
282 | } |
||
283 | |||
284 | 2 | return $countProcessed; |
|
285 | } |
||
286 | |||
287 | 8 | public function deleteJob(\Dtc\QueueBundle\Model\Job $job) |
|
293 | |||
294 | public function saveHistory(\Dtc\QueueBundle\Model\Job $job) |
||
298 | |||
299 | 22 | public function save(\Dtc\QueueBundle\Model\Job $job) |
|
300 | { |
||
301 | // Todo: Serialize args |
||
302 | |||
303 | // Generate crc hash for the job |
||
304 | 22 | $hashValues = array($job->getClassName(), $job->getMethod(), $job->getWorkerName(), $job->getArgs()); |
|
305 | 22 | $crcHash = hash('sha256', serialize($hashValues)); |
|
306 | 22 | $job->setCrcHash($crcHash); |
|
307 | 22 | $objectManager = $this->getObjectManager(); |
|
308 | |||
309 | 22 | if (true === $job->getBatch()) { |
|
310 | // See if similar job that hasn't run exists |
||
311 | $criteria = array('crcHash' => $crcHash, 'status' => BaseJob::STATUS_NEW); |
||
312 | $oldJob = $this->getRepository()->findOneBy($criteria); |
||
313 | |||
314 | if ($oldJob) { |
||
315 | // Old job exists - just override fields Set higher priority |
||
316 | $oldJob->setPriority(max($job->getPriority(), $oldJob->getPriority())); |
||
317 | $oldJob->setWhenAt(min($job->getWhenAt(), $oldJob->getWhenAt())); |
||
318 | $oldJob->setBatch(true); |
||
319 | $objectManager->persist($oldJob); |
||
320 | $objectManager->flush(); |
||
321 | |||
322 | return $oldJob; |
||
323 | } |
||
324 | } |
||
325 | |||
326 | // Just save a new job |
||
327 | 22 | View Code Duplication | if (!$job->getId() && $objectManager instanceof EntityManager) { |
328 | 11 | if (null !== self::$resetInsertCalled && spl_object_hash($objectManager) === self::$resetInsertCalled) { |
|
329 | // Insert SQL is cached... |
||
330 | throw new \Exception("Can't call save and reset within the same process cycle"); |
||
331 | } |
||
332 | 11 | self::$saveInsertCalled = spl_object_hash($objectManager); |
|
333 | } |
||
334 | 22 | $objectManager->persist($job); |
|
335 | 22 | $objectManager->flush(); |
|
336 | |||
337 | 22 | return $job; |
|
338 | } |
||
339 | |||
340 | /** |
||
341 | * @param string $objectName |
||
342 | */ |
||
343 | abstract protected function stopIdGenerator($objectName); |
||
344 | |||
345 | abstract protected function restoreIdGenerator($objectName); |
||
346 | |||
347 | /** |
||
348 | * @param int $limit |
||
349 | * @param int $offset |
||
350 | */ |
||
351 | 2 | private function resetJobsByCriterion( |
|
352 | $criterion, |
||
353 | $limit, |
||
354 | $offset) |
||
408 | } |
||
409 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.