Elgg  Version 2.3
Mutex.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Database;
4 
14 class Mutex {
15 
19  private $db;
20 
24  private $logger;
25 
32  public function __construct(\Elgg\Database $db, \Elgg\Logger $logger) {
33  $this->db = $db;
34  $this->logger = $logger;
35  }
36 
43  public function lock($namespace) {
44  $this->assertNamespace($namespace);
45 
46  if (!$this->isLocked($namespace)) {
47  // Lock it
48  $this->db->insertData("CREATE TABLE {$this->db->prefix}{$namespace}_lock (id INT)");
49  $this->logger->info("Locked mutex for $namespace");
50  return true;
51  }
52 
53  $this->logger->warn("Cannot lock mutex for {$namespace}: already locked.");
54  return false;
55  }
56 
63  public function unlock($namespace) {
64  $this->assertNamespace($namespace);
65 
66  $this->db->deleteData("DROP TABLE {$this->db->prefix}{$namespace}_lock");
67  $this->logger->notice("Mutex unlocked for $namespace.");
68  }
69 
76  public function isLocked($namespace) {
77  $this->assertNamespace($namespace);
78 
79  return (bool) count($this->db->getData("SHOW TABLES LIKE '{$this->db->prefix}{$namespace}_lock'"));
80  }
81 
89  private function assertNamespace($namespace) {
90  if (!ctype_alpha($namespace)) {
91  throw new InvalidParameterException("Mutex namespace can only have characters [A-Za-z].");
92  }
93  }
94 }
The Elgg database.
Definition: Database.php:17
WARNING: API IN FLUX.
Definition: Mutex.php:14
Save menu items.
isLocked($namespace)
Checks if mutex is locked.
Definition: Mutex.php:76
lock($namespace)
Creates a table {prefix}{$namespace}_lock that is used as a mutex.
Definition: Mutex.php:43
__construct(\Elgg\Database $db,\Elgg\Logger $logger)
Constructor.
Definition: Mutex.php:32
unlock($namespace)
Unlocks mutex.
Definition: Mutex.php:63