private function buildFormula()
    {
        $numCategories = \count($this->categories);
        switch ($numCategories) {
            case 1:
                // Just one category
                return '0';
            case 2:
                return self::reduceFormula(self::reverseFormula($this->categories[0]->formula));
            default:
                $formula = (string) ($numCategories - 1);
                for ($i = $numCategories - 2; $i >= 0; $i--) {
                    $fl = self::reduceFormula($this->categories[$i]->formula);
                    if (!\preg_match('/^\([^()]+\)$/', $fl)) {
                        $fl = "($fl)";
                    }
                    $formula = "$fl ? $i : $formula";
                    if ($i > 0) {
                        $formula = "($formula)";
                    }
                }

                return $formula;
        }
    }