<?php
namespace App\Utility;

use Cake\ORM\TableRegistry;

class SchemaUtility
{
    // Cache schemas for tables
    protected static $cachedSchemas = [];

    // Cache specific column existence for faster lookups
    protected static $columnCache = [];

    /**
     * Check if the specified column exists in the given table schema.
     *
     * @param string $table The name of the table.
     * @param string $column The column name to check.
     * @return bool True if the column exists, False otherwise.
     */
    public static function hasColumn($table, $column)
    {
        // Cache check for the specific table/column combo to prevent redundant lookups
        if (isset(self::$columnCache[$table][$column])) {
            return self::$columnCache[$table][$column];
        }

        // Load and cache the schema if not cached
        if (!isset(self::$cachedSchemas[$table])) {
            $tableObject = TableRegistry::getTableLocator()->get($table);
            self::$cachedSchemas[$table] = $tableObject->getSchema()->columns();
        }

        // Check if the column exists in the cached schema
        $hasColumn = in_array($column, self::$cachedSchemas[$table]);

        // Cache the column existence result for future queries
        self::$columnCache[$table][$column] = $hasColumn;

        return $hasColumn;
    }
}
