1<?php
2/**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 */
8
9namespace Piwik\Plugins\CoreHome\Columns\Metrics;
10
11use Piwik\DataTable;
12use Piwik\DataTable\Row;
13use Piwik\Metrics\Formatter;
14use Piwik\Piwik;
15use Piwik\Plugin\ProcessedMetric;
16use Piwik\Plugin\Report;
17
18/**
19 * Percent of visits in the whole table. Calculated as:
20 *
21 *     nb_visits / sum(all nb_visits in table)
22 *
23 * nb_visits is calculated by core archiving process.
24 */
25class VisitsPercent extends ProcessedMetric
26{
27    private $cachedTotalVisits = null;
28    private $forceTotalVisits = null;
29
30    /**
31     * Constructor.
32     *
33     * @param int|null $totalVisits The forced value of total visits to use.
34     */
35    public function __construct($totalVisits = null)
36    {
37        $this->forceTotalVisits = $totalVisits;
38    }
39
40    public function getName()
41    {
42        return 'nb_visits_percentage';
43    }
44
45    public function getTranslatedName()
46    {
47        return Piwik::translate('General_ColumnPercentageVisits');
48    }
49
50    public function compute(Row $row)
51    {
52        $visits = $this->getMetric($row, 'nb_visits');
53
54        return Piwik::getQuotientSafe($visits, $this->cachedTotalVisits, $precision = 2);
55    }
56
57    public function format($value, Formatter $formatter)
58    {
59        return $formatter->getPrettyPercentFromQuotient($value);
60    }
61
62    public function getDependentMetrics()
63    {
64        return array('nb_visits');
65    }
66
67    public function beforeCompute($report, DataTable $table)
68    {
69        if ($this->forceTotalVisits === null) {
70            $this->cachedTotalVisits = array_sum($this->getMetricValues($table, 'nb_visits'));
71        } else {
72            $this->cachedTotalVisits = $this->forceTotalVisits;
73        }
74
75        return true; // always compute
76    }
77}