-
Notifications
You must be signed in to change notification settings - Fork 988
/
SmartColumnTypeTrait.php
49 lines (45 loc) · 1.54 KB
/
SmartColumnTypeTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
trait SmartColumnTypeTrait
{
/**
* Splits a column type into 3 parts:
* - The base type.
* - Any parameters that must be passed between brackets (brackets are ommitted).
* - Any arguments that must be appended.
* @param string $type
*/
protected function splitColumnType($type) {
$regex = '/^([a-zA-Z ]+)\s*(\(.+\))?\s*(.*)$/';
if (preg_match($regex, $type, $matches)) {
return [
'base' => trim($matches[1]),
'arguments' => substr($matches[2], 1, -1),
'suffix' => $matches[3]
];
}
throw new \Exception("Could not parse type.");
}
protected function parseType($type, callable $baseParser)
{
$parts = $this->splitColumnType($type);
$base = $baseParser($parts['base']);
$baseParts = $this->splitColumnType($base);
if (!empty($parts['arguments'])) {
$baseParts['arguments'] = $parts['arguments'];
$result = $baseParts['base'] . (!empty($baseParts['arguments']) ? "({$baseParts['arguments']}) " : " ") . $parts['suffix'];
} else {
$result = $base;
}
return $result;
}
/**
* Adds support for replacing default arguments.
* @param string $type
* @return string
*/
public function getColumnType($type)
{
// This is bad practice, it assumes knowledge about the traits' parent.
return $this->parseType($type, function($type) { return parent::getColumnType($type); });
}
}