| 1 |
<?php //phpcs:ignore |
| 2 |
|
| 3 |
/** |
| 4 |
* BaseController — shared period helpers for analytics controllers. |
| 5 |
* |
| 6 |
* @package Disco |
| 7 |
* @subpackage Disco\App\Analytics\Controllers |
| 8 |
* @since 1.3.37 |
| 9 |
*/ |
| 10 |
|
| 11 |
namespace Disco\App\Analytics\Controllers; |
| 12 |
|
| 13 |
/** |
| 14 |
* Shared period-resolution helpers used by every analytics controller. |
| 15 |
* |
| 16 |
* No SQL and no query building here — date math only. |
| 17 |
*/ |
| 18 |
abstract class BaseController { |
| 19 |
|
| 20 |
/** |
| 21 |
* Resolves the current period, defaulting to the last 28 days ending today. |
| 22 |
* |
| 23 |
* @param array $args Request args with optional date_from / date_to (Y-m-d). |
| 24 |
* @return array { from: string, to: string } |
| 25 |
*/ |
| 26 |
protected static function resolve_current_period( array $args ): array { |
| 27 |
if ( ! empty( $args['date_to'] ) ) { |
| 28 |
$to = $args['date_to']; |
| 29 |
} else { |
| 30 |
$to = gmdate( 'Y-m-d' ); |
| 31 |
} |
| 32 |
|
| 33 |
if ( ! empty( $args['date_from'] ) ) { |
| 34 |
$from = $args['date_from']; |
| 35 |
} else { |
| 36 |
$from = gmdate( 'Y-m-d', strtotime( '-27 days', strtotime( $to ) ) ); |
| 37 |
} |
| 38 |
|
| 39 |
return array( |
| 40 |
'from' => $from, |
| 41 |
'to' => $to, |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Resolves the comparison period as the same duration immediately before the current period. |
| 47 |
* |
| 48 |
* @param array $current Period array with from and to date strings. |
| 49 |
* @return array { from: string, to: string } |
| 50 |
*/ |
| 51 |
protected static function resolve_compare_period( array $current ): array { |
| 52 |
if ( ! $current['from'] || ! $current['to'] ) { |
| 53 |
return array( |
| 54 |
'from' => '', |
| 55 |
'to' => '', |
| 56 |
); |
| 57 |
} |
| 58 |
|
| 59 |
$duration = (int) round( ( strtotime( $current['to'] ) - strtotime( $current['from'] ) ) / DAY_IN_SECONDS ); |
| 60 |
$compare_to = gmdate( 'Y-m-d', strtotime( $current['from'] ) - DAY_IN_SECONDS ); |
| 61 |
$compare_from = gmdate( 'Y-m-d', strtotime( $compare_to ) - $duration * DAY_IN_SECONDS ); |
| 62 |
|
| 63 |
return array( |
| 64 |
'from' => $compare_from, |
| 65 |
'to' => $compare_to, |
| 66 |
); |
| 67 |
} |
| 68 |
|
| 69 |
} |
| 70 |
|