1: <?php
2:
3: namespace malkusch\bav;
4:
5: /**
6: * Container for DataBackend objects.
7: *
8: * @author Markus Malkusch <markus@malkusch.de>
9: * @link bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK Donations
10: * @license GPL
11: * @see DataBackend
12: * @api
13: */
14: abstract class DataBackendContainer
15: {
16:
17: /**
18: * @var string Name of the installation lock file
19: */
20: const INSTALL_LOCK = "bav_install.lock";
21:
22: /**
23: * @var DataBackend
24: */
25: private $backend;
26:
27: /**
28: * Returns the unconfigured backend which is only created by calling the
29: * constructor.
30: *
31: * @return DataBackend
32: */
33: abstract protected function makeDataBackend();
34:
35: /**
36: * Builds a configured data backend.
37: *
38: * If configured this method would automatically install the backend. I.e. a first
39: * call will take some amount of time.
40: *
41: * @return DataBackend
42: * @throws DataBackendException
43: */
44: private function buildDataBackend()
45: {
46: $configuration = ConfigurationRegistry::getConfiguration();
47: $backend = $this->makeDataBackend();
48:
49: // Installation
50: if ($configuration->isAutomaticInstallation() && ! $backend->isInstalled()) {
51: $lock = new Lock(self::INSTALL_LOCK);
52: $lock->executeOnce(
53: function () use ($backend) {
54: $backend->install();
55: }
56: );
57: }
58:
59: // Update hook
60: register_shutdown_function(array($this, "applyUpdatePlan"), $backend);
61:
62: return $backend;
63: }
64:
65: /**
66: * Shut down hook for applying the update plan.
67: */
68: public function applyUpdatePlan(DataBackend $backend)
69: {
70: $plan = ConfigurationRegistry::getConfiguration()->getUpdatePlan();
71: if ($plan != null && $plan->isOutdated($backend)) {
72: $plan->perform($backend);
73:
74: }
75: }
76:
77: /**
78: * Returns a configured data backend.
79: *
80: * If configured this method would automatically install and update the backend. I.e.
81: * some calls might take longer.
82: *
83: * @see Configuration::setAutomaticInstallation()
84: * @see DataBackend::install()
85: * @return DataBackend
86: */
87: public function getDataBackend()
88: {
89: if (is_null($this->backend)) {
90: $this->backend = $this->buildDataBackend();
91:
92: }
93: return $this->backend;
94: }
95: }
96: