Elgg  Version master
Mutex.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Database;
4 
5 use Elgg\Database;
7 use Elgg\Traits\Loggable;
8 
18 class Mutex {
19 
20  use Loggable;
21 
27  public function __construct(protected Database $db) {
28  }
29 
37  public function lock(string $namespace): bool {
38  $this->assertNamespace($namespace);
39 
40  if (!$this->isLocked($namespace)) {
41  // Lock it
42  $this->db->getConnection('write')->executeStatement("CREATE TABLE {$this->db->prefix}{$namespace}_lock (id INT)");
43 
44  $this->getLogger()->info("Locked mutex for {$namespace}");
45  return true;
46  }
47 
48  $this->getLogger()->warning("Cannot lock mutex for {$namespace}: already locked.");
49  return false;
50  }
51 
59  public function unlock(string $namespace): void {
60  $this->assertNamespace($namespace);
61 
62  $this->db->getConnection('write')->executeStatement("DROP TABLE {$this->db->prefix}{$namespace}_lock");
63 
64  $this->getLogger()->notice("Mutex unlocked for {$namespace}.");
65  }
66 
74  public function isLocked(string $namespace): bool {
75  $this->assertNamespace($namespace);
76 
77  $result = $this->db->getConnection('read')->executeQuery("SHOW TABLES LIKE '{$this->db->prefix}{$namespace}_lock'");
78  return $result->rowCount() > 0;
79  }
80 
89  protected function assertNamespace(string $namespace): void {
90  if (!ctype_alpha($namespace)) {
91  throw new InvalidArgumentException('Mutex namespace can only have characters [A-Za-z].');
92  }
93  }
94 }
Provides database mutex that can be used to prevent race conditions between two processes that affect...
Definition: Mutex.php:18
assertNamespace(string $namespace)
Assert that the namespace contains only characters [A-Za-z].
Definition: Mutex.php:89
unlock(string $namespace)
Unlocks mutex.
Definition: Mutex.php:59
lock(string $namespace)
Creates a table {prefix}{$namespace}_lock that is used as a mutex.
Definition: Mutex.php:37
isLocked(string $namespace)
Checks if mutex is locked.
Definition: Mutex.php:74
__construct(protected Database $db)
Constructor.
Definition: Mutex.php:27
The Elgg database.
Definition: Database.php:26
Exception thrown if an argument is not of the expected type.
foreach($recommendedExtensions as $extension) if(empty(ini_get('session.gc_probability'))||empty(ini_get('session.gc_divisor'))) $db
if(parse_url(elgg_get_site_url(), PHP_URL_PATH) !=='/') if(file_exists(elgg_get_root_path() . 'robots.txt'))
Set robots.txt.
Definition: robots.php:10