Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ForeignKey.php
Go to the documentation of this file.
1 <?php
8 
14 
24 {
28  const FOREIGN_KEY_STATEMENT = 'FOREIGN KEY';
29 
33  private $resourceConnection;
34 
40  public function __construct(ResourceConnection $resourceConnection)
41  {
42  $this->resourceConnection = $resourceConnection;
43  }
44 
48  public function toDefinition(ElementInterface $foreignKey)
49  {
50  $adapter = $this->resourceConnection->getConnection(
51  $foreignKey->getTable()->getResource()
52  );
53  $referenceTable = $this->resourceConnection->getTableName(
54  $foreignKey->getReferenceTable()->getName()
55  );
56  //CONSTRAINT `fk_name` FOREIGN KEY (`column`) REFERENCES `table` (`column`) option
57  $foreignKeySql = sprintf(
58  "CONSTRAINT %s %s (%s) REFERENCES %s (%s) %s",
59  $adapter->quoteIdentifier($foreignKey->getName()),
60  self::FOREIGN_KEY_STATEMENT,
61  $adapter->quoteIdentifier($foreignKey->getColumn()->getName()),
62  $adapter->quoteIdentifier($referenceTable),
63  $adapter->quoteIdentifier($foreignKey->getReferenceColumn()->getName()),
64  $foreignKey->getOnDelete() ? sprintf(" ON DELETE %s", $foreignKey->getOnDelete()) : ''
65  );
66 
67  return $foreignKeySql;
68  }
69 
73  public function fromDefinition(array $data)
74  {
75  if (!isset($data['Create Table'])) {
76  throw new LocalizedException(
77  new \Magento\Framework\Phrase('Can`t read foreign keys from current database')
78  );
79  }
80 
81  $createMySQL = $data['Create Table'];
82  $ddl = [];
83  $regExp = '#,\s*CONSTRAINT\s*`([^`]*)`\s*FOREIGN KEY\s*?\(`([^`]*)`\)\s*'
84  . 'REFERENCES\s*(`([^`]*)`\.)?`([^`]*)`\s*\(`([^`]*)`\)\s*'
85  . '(\s*ON\s+DELETE\s*(RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT))?'
86  . '(\s*ON\s+UPDATE\s*(RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT))?#';
87  $matches = [];
88 
89  if (preg_match_all($regExp, $createMySQL, $matches, PREG_SET_ORDER)) {
90  foreach ($matches as $match) {
91  $ddl[$match[1]] = [
92  'type' => Reference::TYPE,
93  'name' => $match[1],
94  'column' => $match[2],
95  'referenceTable' => $match[5],
96  'referenceColumn' => $match[6],
97  'onDelete' => isset($match[7]) ? $match[8] : 'NO ACTION'
98  ];
99  }
100  }
101 
102  return $ddl;
103  }
104 }
$adapter
Definition: webapi_user.php:16