Passed
Push — master ( 7d0739...4a2912 )
by Iman
03:52
created

DbInspector::listTables()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use Cache;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, crocodicstudio\crudbooster\helpers\Cache. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use crocodicstudio\crudbooster\helpers\Cache as CbCache;
7
use DB;
8
use Illuminate\Support\Facades\Schema;
9
10
class DbInspector
11
{
12
    /**
13
     * @param $table
14
     * @return bool|null|string
15
     * @throws \Exception
16
     */
17
    public static function findPK($table)
18
    {
19
        if (! $table) {
20
            return 'id';
21
        }
22
23
        if (CbCache::get('table_'.$table, 'primaryKey')) {
24
            return CbCache::get('table_'.$table, 'primaryKey');
25
        }
26
        $table = CRUDBooster::parseSqlTable($table);
27
28
        if (! $table['table']) {
29
            throw new \Exception("parseSqlTable can't determine the table");
30
        }
31
32
        $primaryKey = self::findPKname($table);
33
34
        if (! $primaryKey) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $primaryKey of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
35
            return 'id';
36
        }
37
        CbCache::put('table_'.$table, 'primaryKey', $primaryKey);
38
39
        return $primaryKey;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $primaryKey returns the type array which is incompatible with the documented return type null|string|boolean.
Loading history...
40
    }
41
42
    /**
43
     * @param $table
44
     * @param $field
45
     * @return bool
46
     */
47
    public static function isNullableColumn($table, $field)
48
    {
49
        return !\DB::getDoctrineSchemaManager()->listTableColumns($table)[$field]->getNotnull();
50
    }
51
52
    /**
53
     * @param $columns
54
     * @return string
55
     */
56
    public static function colName($columns)
57
    {
58
        $nameColCandidate = explode(',', cbConfig('NAME_FIELDS_CANDIDATE'));
59
60
        foreach ($columns as $c) {
61
            foreach ($nameColCandidate as $cc) {
62
                if (strpos($c, $cc) !== false) {
63
                    return $c;
64
                }
65
            }
66
        }
67
68
        return 'id';
69
    }
70
71
    /**
72
     * @param $fieldName
73
     * @return bool
74
     */
75
    public static function isForeignKey($fieldName)
76
    {
77
        $cacheKey = 'isForeignKey_'.$fieldName;
78
79
        if (Cache::has($cacheKey)) {
80
            return Cache::get($cacheKey);
81
        }
82
83
        $table = self::getTableForeignKey($fieldName);
84
        if (! $table) {
85
            return false;
86
        }
87
88
        $hasTable = Schema::hasTable($table);
89
        Cache::forever($cacheKey, $hasTable);
90
91
        return $hasTable;
92
    }
93
94
    /**
95
     * @param $table
96
     * @return null
97
     */
98
    private static function getPKforSqlServer($table)
99
    {
100
        try {
101
            $query = "
102
						SELECT Col.Column_Name,Col.Table_Name from 
103
						    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
104
						    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
105
						WHERE 
106
						    Col.Constraint_Name = Tab.Constraint_Name
107
						    AND Col.Table_Name = Tab.Table_Name
108
						    AND Constraint_Type = 'PRIMARY KEY'
109
							AND Col.Table_Name = '$table[table]' 
110
					";
111
            $keys = DB::select($query);
112
            $primaryKey = $keys[0]->Column_Name;
113
        } catch (\Exception $e) {
114
            $primaryKey = null;
115
        }
116
117
        return $primaryKey;
118
    }
119
120
    /**
121
     * @param $table
122
     * @return array
123
     */
124
    private static function findPKname($table)
125
    {
126
        if (env('DB_CONNECTION') == 'sqlsrv') {
127
            return self::getPKforSqlServer($table);
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::getPKforSqlServer($table) targeting crocodicstudio\crudboost...or::getPKforSqlServer() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
128
        }
129
        try {
130
            $query = "select * from information_schema.COLUMNS where TABLE_SCHEMA = '$table[database]' and TABLE_NAME = '$table[table]' and COLUMN_KEY = 'PRI'";
131
            $keys = DB::select($query);
132
            $primaryKey = $keys[0]->COLUMN_NAME;
133
        } catch (\Exception $e) {
134
            $primaryKey = null;
135
        }
136
137
        return $primaryKey;
138
    }
139
140
    public static function listTables()
141
    {
142
        return \DB::getDoctrineSchemaManager()->listTableNames();
143
    }
144
145
    public static function getForeignKey($parent_table, $child_table)
146
    {
147
        $parent_table = CRUDBooster::parseSqlTable($parent_table)['table'];
148
        $child_table = CRUDBooster::parseSqlTable($child_table)['table'];
149
150
        if (\Schema::hasColumn($child_table, 'id_'.$parent_table)) {
151
            return 'id_'.$parent_table;
152
        }
153
        return $parent_table.'_id';
154
    }
155
156
    public static function getTableForeignKey($fieldName)
157
    {
158
        if (self::isForeignKey($fieldName)) {
159
            return str_replace(['_id', 'id_'], '', $fieldName);
160
        }
161
    }
162
}