Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Database.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
16 
21 {
25  private $resource;
26 
30  private $deploymentConfig;
31 
35  private $prefix;
36 
40  private $currentLock = false;
41 
47  public function __construct(
48  ResourceConnection $resource,
49  DeploymentConfig $deploymentConfig,
50  string $prefix = null
51  ) {
52  $this->resource = $resource;
53  $this->deploymentConfig = $deploymentConfig;
54  $this->prefix = $prefix;
55  }
56 
66  public function lock(string $name, int $timeout = -1): bool
67  {
68  $name = $this->addPrefix($name);
69 
75  if ($this->currentLock) {
76  throw new AlreadyExistsException(
77  new Phrase(
78  'Current connection is already holding lock for $1, only single lock allowed',
79  [$this->currentLock]
80  )
81  );
82  }
83 
84  $result = (bool)$this->resource->getConnection()->query(
85  "SELECT GET_LOCK(?, ?);",
86  [(string)$name, (int)$timeout]
87  )->fetchColumn();
88 
89  if ($result === true) {
90  $this->currentLock = $name;
91  }
92 
93  return $result;
94  }
95 
103  public function unlock(string $name): bool
104  {
105  $name = $this->addPrefix($name);
106 
107  $result = (bool)$this->resource->getConnection()->query(
108  "SELECT RELEASE_LOCK(?);",
109  [(string)$name]
110  )->fetchColumn();
111 
112  if ($result === true) {
113  $this->currentLock = false;
114  }
115 
116  return $result;
117  }
118 
126  public function isLocked(string $name): bool
127  {
128  $name = $this->addPrefix($name);
129 
130  return (bool)$this->resource->getConnection()->query(
131  "SELECT IS_USED_LOCK(?);",
132  [(string)$name]
133  )->fetchColumn();
134  }
135 
145  private function addPrefix(string $name): string
146  {
147  $name = $this->getPrefix() . '|' . $name;
148 
149  if (strlen($name) > 64) {
150  throw new InputException(new Phrase('Lock name too long: %1...', [substr($name, 0, 64)]));
151  }
152 
153  return $name;
154  }
155 
161  private function getPrefix(): string
162  {
163  if ($this->prefix === null) {
164  $this->prefix = (string)$this->deploymentConfig->get(
166  . '/'
168  ''
169  );
170  }
171 
172  return $this->prefix;
173  }
174 }
__construct(ResourceConnection $resource, DeploymentConfig $deploymentConfig, string $prefix=null)
Definition: Database.php:47
$resource
Definition: bulk.php:12
$deploymentConfig
lock(string $name, int $timeout=-1)
Definition: Database.php:66
if(!isset($_GET['name'])) $name
Definition: log.php:14