<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\Doctrine;

/**
 * Génère les requêtes SQL nécessaires à la configuration de la
 * Row-Level Security (RLS) pour les tables Doctrine.
 *
 * ---
 *
 * ## Rôle
 * Cette fabrique crée les instructions SQL permettant :
 * - d’activer une politique RLS (`CREATE POLICY`, `ENABLE ROW LEVEL SECURITY`, etc.)
 * - de désactiver une politique RLS (`DROP POLICY`, `DISABLE ROW LEVEL SECURITY`)
 *
 * ---
 *
 * ## Exemple
 * ```
 * $factory = new RowLevelSecuritySqlFactory();
 * $sqls = $factory->createEnableSqls('user_policy', '"user"', 'app_user', 'owner_id = current_user_id()', 'ALL', true);
 * ```
 *
 * ---
 *
 * @see \Serenity\CoreBundle\Doctrine\EventListener\RowLevelSecurityListener
 */
class RowLevelSecuritySqlBuilder
{
    /**
     * @return array<string>
     */
    public function createEnableSqls(string $policy, string $table, string $role, string $using, string $for, bool $withCheck): array
    {
        return [
            \sprintf('CREATE POLICY %s ON %s FOR %s TO %s USING (%s) WITH CHECK (%d)', $policy, $table, $for, $role, $using, $withCheck),
            \sprintf('GRANT ALL ON TABLE %s TO %s', $table, $role),
            \sprintf('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', $table),
            \sprintf('ALTER TABLE %s FORCE ROW LEVEL SECURITY', $table),
        ];
    }
}
