Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
DatabaseUtility
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
3.03
0.00% covered (danger)
0.00%
0 / 1
 tableExists
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
3.03
1<?php
2declare(strict_types=1);
3
4namespace App\Utility;
5
6use Cake\Datasource\ConnectionManager;
7
8/**
9 * Class DatabaseUtility
10 *
11 * This utility class provides a method to check if a table exists in the database.
12 */
13class DatabaseUtility
14{
15    /**
16     * Check if a table exists in the database.
17     *
18     * @param string $tableName The name of the table to check.
19     * @return bool True if the table exists, false otherwise.
20     */
21    public static function tableExists(string $tableName): bool
22    {
23        // Get the default database connection
24        $connection = ConnectionManager::get('default');
25
26        $dbDatabase = null;
27
28        if (!empty($connection->config()['database'])) {
29            $dbDatabase = $connection->config()['database'];
30        } else {
31            return false;
32        }
33
34        // Define the query to check for the table's existence
35        $query = "SELECT COUNT(*) FROM information_schema.tables
36                  WHERE table_schema = :table_schema
37                  AND table_name = :table_name";
38
39        // Execute the query with the provided table name and database schema
40        /** @var \Cake\Database\Connection $connection */
41        $result = $connection->execute($query, [
42            'table_schema' => $dbDatabase,
43            'table_name' => $tableName,
44        ])->fetch('assoc');
45
46        // Check if the table exists and the database name is valid
47        if (!is_array($result)) {
48            return false;
49        }
50
51        return !empty(array_values($result)[0]);
52    }
53}