StatsController::dashboard()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 1
eloc 10
nc 1
nop 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Carbon\CarbonInterval;
6
use App\Repositories\ProductRepository;
7
use App\Repositories\SaleRepository;
8
use Exception;
9
10
class StatsController extends Controller {
11
    
12
    const DEFAULT_INTERVAL = '15d';
13
14
    protected $saleRepository;
15
    protected $productRepository;
16
17
    public function __construct(SaleRepository $saleRepository, ProductRepository $productRepository)
18
    {
19
        $this->saleRepository = $saleRepository;
20
        $this->productRepository = $productRepository;
21
    }
22
23
    public function dashboard($interval=self::DEFAULT_INTERVAL)
24
    {
25
        $intervalData = $this->extractIntervalData($interval);
26
27
        $sales = $this->saleRepository->countByInterval($intervalData);
28
        $users = $this->saleRepository->rankUsersByInterval($intervalData);
29
        $products = $this->productRepository->rankBySalesInInterval($intervalData);
30
31
        $title = $this->getTitleFromInterval($intervalData);
32
33
        return view('stats.app')->with('title', $title)
34
                                ->with('sales', $sales)
35
                                ->with('users', $users)
36
                                ->with('products', $products);
37
    }
38
39
    /**
40
     * Extracts a Carbon interval from the short notation (30d, 4h, ...) used in the URL
41
     *
42
     * @param $intervalString
43
     * @return CarbonInterval
44
     * @throws Exception
45
     */
46
    private function extractIntervalData($intervalString)
47
    {
48
        $type = substr($intervalString, -1);
49
        $nb = intval(substr($intervalString, 0, -1));
50
51
        if( $type=='h' )
52
        {
53
            if( $nb>24 )
54
            {
55
                $nb = 24;
56
            }
57
58
            return CarbonInterval::hours($nb);
59
        }
60
        elseif( $type=='d' )
61
        {
62
            if( $nb>30 )
63
            {
64
                $nb = 30;
65
            }
66
67
            return CarbonInterval::days($nb);
68
        }
69
70
        throw new Exception('Could not extract interval data from '.$intervalString);
71
    }
72
73
    /**
74
     * Transforms a Carbon interval in a readable string (last 8 hours, ...)
75
     *
76
     * @param CarbonInterval $interval
77
     * @return string
78
     */
79
    private function getTitleFromInterval(CarbonInterval $interval)
80
    {
81
        if( $interval->h>0 )
82
            return 'Last '.$interval->h.' hours';
83
84
        if( $interval->d>0 )
85
            return 'Last '.$interval->d.' days';
86
87
        return 'Last '.$interval->forHumans();
88
    }
89
90
}
91