3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
11 namespace Civi\Core\Lock
;
13 use Civi\Core\Resolver
;
17 * @package Civi\Core\Lock
19 * The lock-manager allows one to define the lock policy -- i.e. given a
20 * specific lock, how does one acquire the lock?
28 * Symbolic name for the lock. Names generally look like
29 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
31 * Categories: worker|data|cache|...
32 * Component: core|mailing|member|contribute|...
33 * @return LockInterface
34 * @throws \CRM_Core_Exception
36 public function create($name) {
37 $factory = $this->getFactory($name);
39 /** @var LockInterface $lock */
40 $lock = call_user_func_array($factory, [$name]);
44 throw new \
CRM_Core_Exception("Lock \"$name\" does not match any rules. Use register() to add more rules.");
49 * Create and attempt to acquire a lock.
51 * Note: Be sure to check $lock->isAcquired() to determine whether
52 * acquisition was successful.
55 * Symbolic name for the lock. Names generally look like
56 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
58 * Categories: worker|data|cache|...
59 * Component: core|mailing|member|contribute|...
60 * @param int|null $timeout
61 * The number of seconds to wait to get the lock.
62 * For a default value, use NULL.
63 * @return LockInterface
64 * @throws \CRM_Core_Exception
66 public function acquire($name, $timeout = NULL) {
67 $lock = $this->create($name);
68 $lock->acquire($timeout);
74 * Symbolic name for the lock.
75 * @return callable|NULL
77 public function getFactory($name) {
78 foreach ($this->rules
as $rule) {
79 if (preg_match($rule['pattern'], $name)) {
80 return Resolver
::singleton()->get($rule['factory']);
87 * Register the lock-factory to use for specific lock-names.
89 * @param string $pattern
90 * A regex to match against the lock name.
91 * @param string|array $factory
92 * A callback. The callback should accept a $name parameter.
93 * Callbacks will be located using the resolver.
97 public function register($pattern, $factory) {
99 'pattern' => $pattern,
100 'factory' => $factory,