Singular_Analytics.php
46 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWP\Public_API; |
| 4 | |
| 5 | use IAWP\Date_Range\Date_Range; |
| 6 | use IAWP\Illuminate_Builder; |
| 7 | use IAWP\Query; |
| 8 | use IAWPSCOPED\Illuminate\Database\Query\JoinClause; |
| 9 | /** @internal */ |
| 10 | class Singular_Analytics |
| 11 | { |
| 12 | public $singular_id; |
| 13 | public $views; |
| 14 | public $visitors; |
| 15 | public $sessions; |
| 16 | private function __construct($singular_id, $row) |
| 17 | { |
| 18 | $this->singular_id = $singular_id; |
| 19 | $this->views = $row->views ?? 0; |
| 20 | $this->visitors = $row->visitors ?? 0; |
| 21 | $this->sessions = $row->sessions ?? 0; |
| 22 | } |
| 23 | /** |
| 24 | * @param string|int $singular_id |
| 25 | * @param Date_Range $date_range |
| 26 | * |
| 27 | * @return self |
| 28 | */ |
| 29 | public static function for($singular_id, Date_Range $date_range) : ?self |
| 30 | { |
| 31 | if (\get_post($singular_id) === null) { |
| 32 | return null; |
| 33 | } |
| 34 | $resources_table = Query::get_table_name(Query::RESOURCES); |
| 35 | $views_table = Query::get_table_name(Query::VIEWS); |
| 36 | $sessions_table = Query::get_table_name(Query::SESSIONS); |
| 37 | $resource_statistics_query = Illuminate_Builder::new(); |
| 38 | $resource_statistics_query->selectRaw('COUNT(DISTINCT views.id) AS views')->selectRaw('COUNT(DISTINCT sessions.visitor_id) AS visitors')->selectRaw('COUNT(DISTINCT sessions.session_id) AS sessions')->from("{$views_table} as views")->join("{$resources_table} AS resources", function (JoinClause $join) { |
| 39 | $join->on('resources.id', '=', 'views.resource_id'); |
| 40 | })->join("{$sessions_table} AS sessions", function (JoinClause $join) { |
| 41 | $join->on('sessions.session_id', '=', 'views.session_id'); |
| 42 | })->where('resources.resource', '=', 'singular')->where('resources.singular_id', '=', $singular_id)->whereBetween('views.viewed_at', [$date_range->iso_start(), $date_range->iso_end()])->groupBy('resources.id'); |
| 43 | return new self((int) $singular_id, $resource_statistics_query->get()->first()); |
| 44 | } |
| 45 | } |
| 46 |