Last active
August 1, 2019 07:01
-
-
Save ManojKiranA/03ea113a4497dcf431213cc7899fea0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JobChunkerJob | |
{ | |
/** | |
* Array of the Request Data. | |
* | |
* @var array|null | |
*/ | |
public $arrayOfData = []; | |
/** | |
* Array of the Chunked Data. | |
* | |
* @var array|null | |
*/ | |
public $arrayOfChunkedData = []; | |
/** | |
* The Class in which the Job needs to be dispatched. | |
* | |
* @var string | |
*/ | |
public $disPatcherClass; | |
/** | |
* Number of Items in the each Chunk. | |
* | |
* @var int | |
*/ | |
public $numberOfItemsPerChunk; | |
/** | |
* Total Number of Chunk. | |
* | |
* @var int | |
*/ | |
public $numberOfChunks; | |
/** | |
* Create a new job instance. DispatchJobByChunking | |
* | |
* @param array $arrayOfData | |
* @param string $disPatcherClass | |
* @param int $numberOfItemsPerChunk | |
* @return void | |
*/ | |
public function __construct($arrayOfData, $disPatcherClass, $queueToDispatchOn = 'default', $numberOfItemsPerChunk = 200) | |
{ | |
$this->arrayOfData = $arrayOfData; | |
$this->disPatcherClass = $disPatcherClass; | |
$this->numberOfItemsPerChunk = $numberOfItemsPerChunk; | |
$this->queueToDispatchOn = $queueToDispatchOn; | |
$this->numberOfChunks = $this->determineNumberofChunk(); | |
$this->arrayOfChunkedData = $this->chunkData(); | |
} | |
/** | |
* Execute the job. | |
* | |
* @return void | |
*/ | |
public function handle() | |
{ | |
$this->dispatchJobByChunk(); | |
} | |
/** | |
* Dispatch the Chunked Array into job | |
* | |
* @return void | |
**/ | |
public function dispatchJobByChunk() | |
{ | |
foreach ($this->arrayOfChunkedData as $eachChunk) { | |
dispatch(new $this->disPatcherClass($eachChunk)) | |
->onQueue($this->queueToDispatchOn); | |
} | |
} | |
/** | |
* Creates the Chunk of Data Redy for dispatching | |
* a new job | |
* | |
* @return array | |
**/ | |
public function chunkData() | |
{ | |
return array_chunk($this->arrayOfData, $this->numberOfChunks); | |
} | |
/** | |
* Calculates the Number of Chunks that can be | |
* Availabe in the current request | |
* | |
* @return int | |
**/ | |
public function determineNumberofChunk() | |
{ | |
$size = ((int) ceil(count($this->arrayOfData) / $this->numberOfItemsPerChunk)); | |
if ($size <= 0) { | |
return 1; | |
} | |
return $size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment