| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\Lib\Migrations; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
|
| 7 |
/** |
| 8 |
* Yoast migrations column class. |
| 9 |
*/ |
| 10 |
class Column { |
| 11 |
|
| 12 |
/** |
| 13 |
* The adapter. |
| 14 |
* |
| 15 |
* @var Adapter |
| 16 |
*/ |
| 17 |
private $adapter; |
| 18 |
|
| 19 |
/** |
| 20 |
* The name. |
| 21 |
* |
| 22 |
* @var string |
| 23 |
*/ |
| 24 |
public $name; |
| 25 |
|
| 26 |
/** |
| 27 |
* The type. |
| 28 |
* |
| 29 |
* @var mixed |
| 30 |
*/ |
| 31 |
public $type; |
| 32 |
|
| 33 |
/** |
| 34 |
* The properties. |
| 35 |
* |
| 36 |
* @var mixed |
| 37 |
*/ |
| 38 |
public $properties; |
| 39 |
|
| 40 |
/** |
| 41 |
* The options. |
| 42 |
* |
| 43 |
* @var array |
| 44 |
*/ |
| 45 |
private $options = []; |
| 46 |
|
| 47 |
/** |
| 48 |
* Creates an instance of a column. |
| 49 |
* |
| 50 |
* @param Adapter $adapter The current adapter. |
| 51 |
* @param string $name The name of the column. |
| 52 |
* @param string $type The type of the column. |
| 53 |
* @param array $options The column options. |
| 54 |
* |
| 55 |
* @throws Exception If invalid arguments provided. |
| 56 |
*/ |
| 57 |
public function __construct( $adapter, $name, $type, $options = [] ) { |
| 58 |
if ( ! $adapter instanceof Adapter ) { |
| 59 |
throw new Exception( 'Invalid Adapter instance.' ); |
| 60 |
} |
| 61 |
if ( empty( $name ) || ! \is_string( $name ) ) { |
| 62 |
throw new Exception( "Invalid 'name' parameter" ); |
| 63 |
} |
| 64 |
if ( empty( $type ) || ! \is_string( $type ) ) { |
| 65 |
throw new Exception( "Invalid 'type' parameter" ); |
| 66 |
} |
| 67 |
$this->adapter = $adapter; |
| 68 |
$this->name = $name; |
| 69 |
$this->type = $type; |
| 70 |
$this->options = $options; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Returns the SQL of this column. |
| 75 |
* |
| 76 |
* @return string |
| 77 |
*/ |
| 78 |
public function to_sql() { |
| 79 |
$column_sql = \sprintf( '%s %s', $this->adapter->identifier( $this->name ), $this->sql_type() ); |
| 80 |
$column_sql .= $this->adapter->add_column_options( $this->type, $this->options ); |
| 81 |
return $column_sql; |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* The SQL string version. |
| 86 |
* |
| 87 |
* @return string |
| 88 |
*/ |
| 89 |
public function __toString() { |
| 90 |
return $this->to_sql(); |
| 91 |
} |
| 92 |
|
| 93 |
/** |
| 94 |
* The SQL type. |
| 95 |
* |
| 96 |
* @return string |
| 97 |
*/ |
| 98 |
private function sql_type() { |
| 99 |
return $this->adapter->type_to_sql( $this->type, $this->options ); |
| 100 |
} |
| 101 |
} |
| 102 |
|