Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ModuleResource.php
Go to the documentation of this file.
1 <?php
8 
9 use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
10 
18 {
24  protected static $schemaVersions = null;
25 
31  protected static $dataVersions = null;
32 
38  protected function _construct()
39  {
40  $this->_init('setup_module', 'module');
41  }
42 
53  protected function _loadVersion($needType)
54  {
55  if ($needType == 'db' && self::$schemaVersions === null ||
56  $needType == 'data' && self::$dataVersions === null
57  ) {
58  self::$schemaVersions = [];
59  // Db version column always exists
60  self::$dataVersions = null;
61  // Data version array will be filled only if Data column exist
62 
63  if ($this->getConnection()->isTableExists($this->getMainTable())) {
64  $select = $this->getConnection()->select()->from($this->getMainTable(), '*');
65  $rowset = $this->getConnection()->fetchAll($select);
66  foreach ($rowset as $row) {
67  self::$schemaVersions[$row['module']] = $row['schema_version'];
68  if (array_key_exists('data_version', $row)) {
69  if (self::$dataVersions === null) {
70  self::$dataVersions = [];
71  }
72  self::$dataVersions[$row['module']] = $row['data_version'];
73  }
74  }
75  }
76  }
77 
78  return $this;
79  }
80 
84  public function getDbVersion($moduleName)
85  {
86  if (!$this->getConnection()) {
87  return false;
88  }
89  $this->_loadVersion('db');
90  return self::$schemaVersions[$moduleName] ?? false;
91  }
92 
96  public function setDbVersion($moduleName, $version)
97  {
98  $dbModuleInfo = ['module' => $moduleName, 'schema_version' => $version];
99 
100  if ($this->getDbVersion($moduleName)) {
101  self::$schemaVersions[$moduleName] = $version;
102  return $this->getConnection()->update(
103  $this->getMainTable(),
104  $dbModuleInfo,
105  ['module = ?' => $moduleName]
106  );
107  } else {
108  self::$schemaVersions[$moduleName] = $version;
109  return $this->getConnection()->insert($this->getMainTable(), $dbModuleInfo);
110  }
111  }
112 
116  public function getDataVersion($moduleName)
117  {
118  if (!$this->getConnection()) {
119  return false;
120  }
121  $this->_loadVersion('data');
122  return self::$dataVersions[$moduleName] ?? false;
123  }
124 
128  public function setDataVersion($moduleName, $version)
129  {
130  $data = ['module' => $moduleName, 'data_version' => $version];
131 
132  if ($this->getDbVersion($moduleName) || $this->getDataVersion($moduleName)) {
133  self::$dataVersions[$moduleName] = $version;
134  $this->getConnection()->update($this->getMainTable(), $data, ['module = ?' => $moduleName]);
135  } else {
136  self::$dataVersions[$moduleName] = $version;
137  $this->getConnection()->insert($this->getMainTable(), $data);
138  }
139  }
140 
148  public static function flush()
149  {
150  self::$dataVersions = null;
151  self::$schemaVersions = [];
152  }
153 }