Passed
Push — master ( 7828f1...cb386f )
by Iman
03:40
created

DbInspector::findPKname()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
rs 9.4285
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 DB;
7
use Illuminate\Support\Facades\Schema;
8
9
class DbInspector
10
{
11
    /**
12
     * @param $table
13
     * @return string
14
     * @throws \Exception
15
     */
16
    public static function findPK(string $table): string
17
    {
18
        if (! $table) {
19
            return 'id';
20
        }
21
22
        return cache()->remember('CrudBooster_pk_'.$table, 10, function () use ($table) {
23
            return self::findPKname($table) ?: 'id';
24
        });
25
    }
26
27
    /**
28
     * @param $table
29
     * @return array
30
     */
31
    private static function findPKname($table)
32
    {
33
        $cols = \DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey()->getColumns();
34
        if (! empty($cols)) {
35
            return $cols[0];
36
        }
37
    }
38
39
    /**
40
     * @param $table
41
     * @param $colName
42
     * @return bool
43
     */
44
    public static function isNullableColumn($table, $colName)
45
    {
46
        $colObj = \DB::getDoctrineSchemaManager()->listTableColumns($table)[$colName];
47
        if (! $colObj) {
48
            return;
49
        }
50
51
        return ! $colObj->getNotnull();
52
    }
53
54
    /**
55
     * @param $columns
56
     * @return string
57
     */
58
    public static function colName(array $columns): string
59
    {
60
        $nameColCandidate = explode(',', cbConfig('NAME_FIELDS_CANDIDATE'));
61
62
        foreach ($columns as $c) {
63
            foreach ($nameColCandidate as $cc) {
64
                if (strpos($c, $cc) !== false) {
65
                    return $c;
66
                }
67
            }
68
        }
69
70
        return 'id';
71
    }
72
73
    /**
74
     * @param $fieldName
75
     * @return bool
76
     */
77
    public static function isForeignKey($fieldName)
78
    {
79
        return Cache::rememberForever('crudbooster_isForeignKey_'.$fieldName, function () use ($fieldName) {
80
            $table = self::getRelatedTableName($fieldName);
81
            return ($table && Schema::hasTable($table));
82
        });
83
    }
84
85
    public static function getRelatedTableName(string $fieldName): string
86
    {
87
        if (starts_with($fieldName, 'id_') || ends_with($fieldName, '_id')) {
88
            return str_replace(['_id', 'id_'], '', $fieldName);
89
        }
90
        return '';
91
    }
92
93
    public static function listTables(): array
94
    {
95
        return \DB::getDoctrineSchemaManager()->listTableNames();
96
    }
97
98
    public static function getForeignKey($parentTable, $childTable): string
99
    {
100
        $parentTable = CRUDBooster::parseSqlTable($parentTable)['table'];
101
        $childTable = CRUDBooster::parseSqlTable($childTable)['table'];
102
103
        if (\Schema::hasColumn($childTable, 'id_'.$parentTable)) {
104
            return 'id_'.$parentTable;
105
        }
106
107
        return $parentTable.'_id';
108
    }
109
}