<?php

function buildSqlForNestingLevel($nestingLevel)
{
    if ($nestingLevel < 2) {
        throw new Exception('Builder works only with 2 and more nesting levels');
    }
    $closingParenthesisCount = $nestingLevel - 1;
    $sql = "SELECT * FROM {$this->table} WHERE path = ? AND parent_id = (";

    while (--$nestingLevel) {
        $sql .= "SELECT id FROM {$this->table} WHERE path = ?";
        if ($nestingLevel > 1) {
            $sql .= ' AND parent_id = (';
        }
    }
    $sql .= str_repeat(')', $closingParenthesisCount);

    return $sql;
}
