| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Modules\Stats\Components; |
| 4 |
|
| 5 |
use ImageOptimization\Classes\Async_Operation\{ |
| 6 |
Async_Operation, |
| 7 |
Async_Operation_Hook, |
| 8 |
Async_Operation_Queue, |
| 9 |
Exceptions\Async_Operation_Exception, |
| 10 |
}; |
| 11 |
use ImageOptimization\Classes\Logger; |
| 12 |
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats; |
| 13 |
|
| 14 |
if ( ! defined( 'ABSPATH' ) ) { |
| 15 |
exit; // Exit if accessed directly. |
| 16 |
} |
| 17 |
|
| 18 |
class Optimization_Stats_Handler { |
| 19 |
/** |
| 20 |
* @async |
| 21 |
* |
| 22 |
* @param $page |
| 23 |
* @param $pages_count |
| 24 |
* @param $output |
| 25 |
* |
| 26 |
* @return void |
| 27 |
*/ |
| 28 |
public function handle_stats_chunk( $page, $pages_count, $output ) { |
| 29 |
$chunk = Optimization_Stats::get_image_stats_chunk( $page ); |
| 30 |
|
| 31 |
foreach ( array_keys( $chunk ) as $key ) { |
| 32 |
if ( isset( $output[ $key ] ) ) { |
| 33 |
$output[ $key ] += $chunk[ $key ]; |
| 34 |
continue; |
| 35 |
} |
| 36 |
|
| 37 |
$output[ $key ] = $chunk[ $key ]; |
| 38 |
} |
| 39 |
|
| 40 |
if ( $page < $pages_count ) { |
| 41 |
try { |
| 42 |
Async_Operation::create( |
| 43 |
Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS, |
| 44 |
[ |
| 45 |
'page' => $page + 1, |
| 46 |
'pages_count' => $pages_count, |
| 47 |
'output' => $output, |
| 48 |
], |
| 49 |
Async_Operation_Queue::STATS |
| 50 |
); |
| 51 |
} catch ( Async_Operation_Exception $aoe ) { |
| 52 |
Logger::log( Logger::LEVEL_ERROR, 'Error while creating a stats calculation task: ' . $aoe->getMessage() ); |
| 53 |
} |
| 54 |
} else { |
| 55 |
unset( $output['pages'] ); |
| 56 |
|
| 57 |
Optimization_Stats::set_stored_stats( $output ); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
public function __construct() { |
| 62 |
add_action( Async_Operation_Hook::CALCULATE_OPTIMIZATION_STATS, [ $this, 'handle_stats_chunk' ], 10, 3 ); |
| 63 |
} |
| 64 |
} |
| 65 |
|