1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
5
|
|
|
* @license https://github.com/flipboxfactory/craft-integration/blob/master/LICENSE |
6
|
|
|
* @link https://github.com/flipboxfactory/craft-integration/ |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace flipbox\craft\integration\records; |
10
|
|
|
|
11
|
|
|
use Craft; |
12
|
|
|
use yii\db\Exception; |
13
|
|
|
use yii\db\MigrationInterface; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @author Flipbox Factory <[email protected]> |
17
|
|
|
* @since 2.2.2 |
18
|
|
|
*/ |
19
|
|
|
trait EnvironmentalTableTrait |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* Identify whether we have ensured the environment table is present |
23
|
|
|
* |
24
|
|
|
* @var bool |
25
|
|
|
*/ |
26
|
|
|
protected static $environmentTableChecked = false; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* The table migration responsible for creating a new table (for an environment) if one |
30
|
|
|
* doesn't already exist. |
31
|
|
|
* |
32
|
|
|
* @return MigrationInterface |
33
|
|
|
*/ |
34
|
|
|
abstract static protected function createEnvironmentTableMigration(): MigrationInterface; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* The name of the environment table. It's suggested to add an environmental suffix to the table. As an |
38
|
|
|
* example: 'your_table_local' where '_local' is the environment. Do not include the table prefix. |
39
|
|
|
* |
40
|
|
|
* @return string |
41
|
|
|
*/ |
42
|
|
|
abstract protected static function environmentTableAlias(): string; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return bool |
46
|
|
|
* @throws \yii\base\NotSupportedException |
47
|
|
|
*/ |
48
|
|
|
protected static function doesEnvironmentTableExist(): bool |
49
|
|
|
{ |
50
|
|
|
return in_array( |
51
|
|
|
Craft::$app->getDb()->tablePrefix . static::environmentTableAlias(), |
52
|
|
|
Craft::$app->getDb()->getSchema()->tableNames, |
53
|
|
|
true |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @throws \Throwable |
59
|
|
|
*/ |
60
|
|
|
public static function ensureEnvironmentTableExists() |
61
|
|
|
{ |
62
|
|
|
if (static::$environmentTableChecked === true) { |
63
|
|
|
return; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
if (!static::doesEnvironmentTableExist() && !static::createEnvironmentTable()) { |
67
|
|
|
throw new Exception(sprintf( |
68
|
|
|
"Unable to create environment table '%s'.", |
69
|
|
|
static::environmentTableAlias() |
70
|
|
|
)); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
static::$environmentTableChecked = true; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return bool |
78
|
|
|
* @throws \Throwable |
79
|
|
|
*/ |
80
|
|
|
protected static function createEnvironmentTable(): bool |
81
|
|
|
{ |
82
|
|
|
ob_start(); |
83
|
|
|
$return = static::createEnvironmentTableMigration()->up(); |
84
|
|
|
ob_end_clean(); |
85
|
|
|
|
86
|
|
|
return $return; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|