Elgg  Version 3.0
Mutex.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Database;
4 
5 use Elgg\Database;
6 use Elgg\Loggable;
8 
18 class Mutex {
19 
20  use Loggable;
21 
25  private $db;
26 
30  private $logger;
31 
38  public function __construct(Database $db, LoggerInterface $logger) {
39  $this->db = $db;
40  $this->logger = $logger;
41  }
42 
49  public function lock($namespace) {
50  $this->assertNamespace($namespace);
51 
52  if (!$this->isLocked($namespace)) {
53  // Lock it
54  $this->db->insertData("CREATE TABLE {$this->db->prefix}{$namespace}_lock (id INT)");
55  $this->logger->info("Locked mutex for $namespace");
56  return true;
57  }
58 
59  $this->logger->warning("Cannot lock mutex for {$namespace}: already locked.");
60  return false;
61  }
62 
69  public function unlock($namespace) {
70  $this->assertNamespace($namespace);
71 
72  $this->db->deleteData("DROP TABLE {$this->db->prefix}{$namespace}_lock");
73  $this->logger->notice("Mutex unlocked for $namespace.");
74  }
75 
82  public function isLocked($namespace) {
83  $this->assertNamespace($namespace);
84 
85  return (bool) count($this->db->getData("SHOW TABLES LIKE '{$this->db->prefix}{$namespace}_lock'"));
86  }
87 
95  private function assertNamespace($namespace) {
96  if (!ctype_alpha($namespace)) {
97  throw new \InvalidParameterException("Mutex namespace can only have characters [A-Za-z].");
98  }
99  }
100 }
trait Loggable
Enables adding a logger.
Definition: Loggable.php:12
WARNING: API IN FLUX.
Definition: Mutex.php:18
__construct(Database $db, LoggerInterface $logger)
Constructor.
Definition: Mutex.php:38
isLocked($namespace)
Checks if mutex is locked.
Definition: Mutex.php:82
lock($namespace)
Creates a table {prefix}{$namespace}_lock that is used as a mutex.
Definition: Mutex.php:49
unlock($namespace)
Unlocks mutex.
Definition: Mutex.php:69