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 */
9
10namespace Piwik\Plugins\CustomDimensions\Dimension;
11
12use \Exception;
13use Piwik\API\Request;
14use Piwik\Plugins\CustomDimensions\Dao\Configuration;
15use Piwik\Plugins\CustomDimensions\Dao\LogTable;
16
17class Index
18{
19    public function getNextIndex($idSite, $scope)
20    {
21        $indexes = $this->getTracking($scope)->getInstalledIndexes();
22
23        $configs = Request::processRequest('CustomDimensions.getConfiguredCustomDimensionsHavingScope', [
24            'idSite' => $idSite,
25            'scope' => $scope,
26        ]);
27        foreach ($configs as $config) {
28            $key = array_search($config['index'], $indexes);
29            if ($key !== false) {
30                unset($indexes[$key]);
31            }
32        }
33
34        if (empty($indexes)) {
35            throw new Exception("All Custom Dimensions for website $idSite in scope '$scope' are already used.");
36        }
37
38        $index = array_shift($indexes);
39
40        return $index;
41    }
42
43    private function getTracking($scope)
44    {
45        return new LogTable($scope);
46    }
47
48    private function getConfiguration()
49    {
50        return new Configuration();
51    }
52}