Completed
Pull Request — master (#13)
by
unknown
02:32
created
src/Module/Exception/ModuleException.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -8,15 +8,15 @@
 block discarded – undo
8 8
 
9 9
 class ModuleException extends \RuntimeException
10 10
 {
11
-	/**
12
-	 * ModuleException constructor.
13
-	 *
14
-	 * @param string $message
15
-	 * @param int $moduleName
16
-	 * @param \Exception|null $previous
17
-	 */
18
-	public function __construct($message, $moduleName, \Exception $previous = null)
19
-	{
20
-		parent::__construct("[$moduleName] " . $message, 0, $previous);
21
-	}
11
+    /**
12
+     * ModuleException constructor.
13
+     *
14
+     * @param string $message
15
+     * @param int $moduleName
16
+     * @param \Exception|null $previous
17
+     */
18
+    public function __construct($message, $moduleName, \Exception $previous = null)
19
+    {
20
+        parent::__construct("[$moduleName] " . $message, 0, $previous);
21
+    }
22 22
 }
23 23
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/RegisterCommand.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -17,24 +17,24 @@
 block discarded – undo
17 17
  */
18 18
 class RegisterCommand extends ModuleCommand
19 19
 {
20
-	/**
21
-	 * {@inheritdoc}
22
-	 */
23
-	protected function configure()
24
-	{
25
-		parent::configure();
20
+    /**
21
+     * {@inheritdoc}
22
+     */
23
+    protected function configure()
24
+    {
25
+        parent::configure();
26 26
 
27
-		$this->setName('module:register')
28
-			->setDescription('Install module');
29
-	}
27
+        $this->setName('module:register')
28
+            ->setDescription('Install module');
29
+    }
30 30
 
31
-	/**
32
-	 * {@inheritdoc}
33
-	 */
34
-	protected function execute(InputInterface $input, OutputInterface $output)
35
-	{
36
-		$module = new Module($input->getArgument('module'));
37
-		$module->register();
38
-		$output->writeln(sprintf('registered <info>%s</info>', $module->getName()));
39
-	}
31
+    /**
32
+     * {@inheritdoc}
33
+     */
34
+    protected function execute(InputInterface $input, OutputInterface $output)
35
+    {
36
+        $module = new Module($input->getArgument('module'));
37
+        $module->register();
38
+        $output->writeln(sprintf('registered <info>%s</info>', $module->getName()));
39
+    }
40 40
 }
41 41
\ No newline at end of file
Please login to merge, or discard this patch.
src/Application/Exception/BitrixException.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -14,37 +14,37 @@
 block discarded – undo
14 14
  */
15 15
 class BitrixException extends \RuntimeException
16 16
 {
17
-	public static function hasException(\CMain $APPLICATION = null)
18
-	{
19
-		if (null === $APPLICATION)
20
-		{
21
-			$APPLICATION = $GLOBALS['APPLICATION'];
22
-		}
17
+    public static function hasException(\CMain $APPLICATION = null)
18
+    {
19
+        if (null === $APPLICATION)
20
+        {
21
+            $APPLICATION = $GLOBALS['APPLICATION'];
22
+        }
23 23
 
24
-		return is_object($APPLICATION->GetException());
25
-	}
24
+        return is_object($APPLICATION->GetException());
25
+    }
26 26
 
27
-	/**
28
-	 * Check for legacy bitrix exception, throws new self if any
29
-	 *
30
-	 * @param string $message [optional] Additional error message
31
-	 * @param \CMain $APPLICATION [optional] $APPLICATION instance
32
-	 * @throws static
33
-	 */
34
-	public static function generate($message = null, \CMain $APPLICATION = null)
35
-	{
36
-		if (null === $APPLICATION)
37
-		{
38
-			$APPLICATION = $GLOBALS['APPLICATION'];
39
-		}
27
+    /**
28
+     * Check for legacy bitrix exception, throws new self if any
29
+     *
30
+     * @param string $message [optional] Additional error message
31
+     * @param \CMain $APPLICATION [optional] $APPLICATION instance
32
+     * @throws static
33
+     */
34
+    public static function generate($message = null, \CMain $APPLICATION = null)
35
+    {
36
+        if (null === $APPLICATION)
37
+        {
38
+            $APPLICATION = $GLOBALS['APPLICATION'];
39
+        }
40 40
 
41
-		if ($ex = $APPLICATION->GetException())
42
-		{
43
-			throw new static($message ? $message . ': ' . $ex->GetString() : $ex->GetString());
44
-		}
45
-		else
46
-		{
47
-			throw new static($message ? $message : 'Unknown exception');
48
-		}
49
-	}
41
+        if ($ex = $APPLICATION->GetException())
42
+        {
43
+            throw new static($message ? $message . ': ' . $ex->GetString() : $ex->GetString());
44
+        }
45
+        else
46
+        {
47
+            throw new static($message ? $message : 'Unknown exception');
48
+        }
49
+    }
50 50
 }
51 51
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/UnregisterCommand.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -17,24 +17,24 @@
 block discarded – undo
17 17
  */
18 18
 class UnregisterCommand extends ModuleCommand
19 19
 {
20
-	/**
21
-	 * {@inheritdoc}
22
-	 */
23
-	protected function configure()
24
-	{
25
-		parent::configure();
20
+    /**
21
+     * {@inheritdoc}
22
+     */
23
+    protected function configure()
24
+    {
25
+        parent::configure();
26 26
 
27
-		$this->setName('module:unregister')
28
-			->setDescription('Uninstall module');
29
-	}
27
+        $this->setName('module:unregister')
28
+            ->setDescription('Uninstall module');
29
+    }
30 30
 
31
-	/**
32
-	 * {@inheritdoc}
33
-	 */
34
-	protected function execute(InputInterface $input, OutputInterface $output)
35
-	{
36
-		$module = new Module($input->getArgument('module'));
37
-		$module->unRegister();
38
-		$output->writeln(sprintf('unregistered <info>%s</info>', $module->getName()));
39
-	}
31
+    /**
32
+     * {@inheritdoc}
33
+     */
34
+    protected function execute(InputInterface $input, OutputInterface $output)
35
+    {
36
+        $module = new Module($input->getArgument('module'));
37
+        $module->unRegister();
38
+        $output->writeln(sprintf('unregistered <info>%s</info>', $module->getName()));
39
+    }
40 40
 }
41 41
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/LoadCommand.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -20,72 +20,72 @@
 block discarded – undo
20 20
  */
21 21
 class LoadCommand extends ModuleCommand
22 22
 {
23
-	use CanRestartTrait;
23
+    use CanRestartTrait;
24 24
 
25
-	/**
26
-	 * {@inheritdoc}
27
-	 */
28
-	protected function configure()
29
-	{
30
-		parent::configure();
25
+    /**
26
+     * {@inheritdoc}
27
+     */
28
+    protected function configure()
29
+    {
30
+        parent::configure();
31 31
 
32
-		$this->setName('module:load')
33
-			->setDescription('Load and install module from Marketplace')
34
-			->addOption('no-update', 'nu', InputOption::VALUE_NONE, 'Don\' update module')
35
-			->addOption('no-register', 'ni', InputOption::VALUE_NONE, 'Load only, don\' register module')
36
-			->addOption('beta', 'b', InputOption::VALUE_NONE, 'Allow the installation of beta releases');
37
-	}
32
+        $this->setName('module:load')
33
+            ->setDescription('Load and install module from Marketplace')
34
+            ->addOption('no-update', 'nu', InputOption::VALUE_NONE, 'Don\' update module')
35
+            ->addOption('no-register', 'ni', InputOption::VALUE_NONE, 'Load only, don\' register module')
36
+            ->addOption('beta', 'b', InputOption::VALUE_NONE, 'Allow the installation of beta releases');
37
+    }
38 38
 
39
-	/**
40
-	 * {@inheritdoc}
41
-	 */
42
-	protected function execute(InputInterface $input, OutputInterface $output)
43
-	{
44
-		$module = new Module($input->getArgument('module'));
39
+    /**
40
+     * {@inheritdoc}
41
+     */
42
+    protected function execute(InputInterface $input, OutputInterface $output)
43
+    {
44
+        $module = new Module($input->getArgument('module'));
45 45
 
46
-		if (!$module->isThirdParty())
47
-		{
48
-			$output->writeln('<info>Loading kernel modules is unsupported</info>');
49
-		}
46
+        if (!$module->isThirdParty())
47
+        {
48
+            $output->writeln('<info>Loading kernel modules is unsupported</info>');
49
+        }
50 50
 
51
-		if ($input->getOption('beta'))
52
-		{
53
-			$module->setBeta();
54
-		}
51
+        if ($input->getOption('beta'))
52
+        {
53
+            $module->setBeta();
54
+        }
55 55
 
56
-		$module->load();
56
+        $module->load();
57 57
 
58
-		if (!$input->getOption('no-update'))
59
-		{
60
-			$modulesUpdated = null;
61
-			while ($module->update($modulesUpdated))
62
-			{
63
-				if (is_array($modulesUpdated))
64
-				{
65
-					foreach ($modulesUpdated as $moduleName => $moduleVersion)
66
-					{
67
-						$output->writeln(sprintf('updated %s to <info>%s</info>', $moduleName, $moduleVersion));
68
-					}
69
-				}
70
-				return $this->restartScript($input, $output);
71
-			}
72
-		}
58
+        if (!$input->getOption('no-update'))
59
+        {
60
+            $modulesUpdated = null;
61
+            while ($module->update($modulesUpdated))
62
+            {
63
+                if (is_array($modulesUpdated))
64
+                {
65
+                    foreach ($modulesUpdated as $moduleName => $moduleVersion)
66
+                    {
67
+                        $output->writeln(sprintf('updated %s to <info>%s</info>', $moduleName, $moduleVersion));
68
+                    }
69
+                }
70
+                return $this->restartScript($input, $output);
71
+            }
72
+        }
73 73
 
74
-		if (!$input->getOption('no-register'))
75
-		{
76
-			try
77
-			{
78
-				$module->register();
79
-			}
80
-			catch (ModuleInstallException $e)
81
-			{
82
-				$output->writeln(sprintf('<comment>%s</comment>', $e->getMessage()), OutputInterface::VERBOSITY_VERBOSE);
83
-				$output->writeln(sprintf('Module loaded, but <error>not registered</error>. You need to do it yourself in admin panel.', $module->getName()));
84
-			}
85
-		}
74
+        if (!$input->getOption('no-register'))
75
+        {
76
+            try
77
+            {
78
+                $module->register();
79
+            }
80
+            catch (ModuleInstallException $e)
81
+            {
82
+                $output->writeln(sprintf('<comment>%s</comment>', $e->getMessage()), OutputInterface::VERBOSITY_VERBOSE);
83
+                $output->writeln(sprintf('Module loaded, but <error>not registered</error>. You need to do it yourself in admin panel.', $module->getName()));
84
+            }
85
+        }
86 86
 
87
-		$output->writeln(sprintf('installed <info>%s</info>', $module->getName()));
87
+        $output->writeln(sprintf('installed <info>%s</info>', $module->getName()));
88 88
 
89
-		return 0;
90
-	}
89
+        return 0;
90
+    }
91 91
 }
92 92
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/UpdateCommand.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -19,38 +19,38 @@
 block discarded – undo
19 19
  */
20 20
 class UpdateCommand extends ModuleCommand
21 21
 {
22
-	use CanRestartTrait;
22
+    use CanRestartTrait;
23 23
 
24
-	/**
25
-	 * {@inheritdoc}
26
-	 */
27
-	protected function configure()
28
-	{
29
-		parent::configure();
24
+    /**
25
+     * {@inheritdoc}
26
+     */
27
+    protected function configure()
28
+    {
29
+        parent::configure();
30 30
 
31
-		$this->setName('module:update')
32
-			->setDescription('Load module updates from Marketplace')
33
-			->addOption('beta', 'b', InputOption::VALUE_NONE, 'Allow the installation of beta releases');
34
-	}
31
+        $this->setName('module:update')
32
+            ->setDescription('Load module updates from Marketplace')
33
+            ->addOption('beta', 'b', InputOption::VALUE_NONE, 'Allow the installation of beta releases');
34
+    }
35 35
 
36
-	/**
37
-	 * {@inheritdoc}
38
-	 */
39
-	protected function execute(InputInterface $input, OutputInterface $output)
40
-	{
41
-		$module = new Module($input->getArgument('module'));
42
-		$modulesUpdated = null;
43
-		while ($module->update($modulesUpdated))
44
-		{
45
-			if (is_array($modulesUpdated))
46
-			{
47
-				foreach ($modulesUpdated as $moduleName => $moduleVersion)
48
-				{
49
-					$output->writeln(sprintf('updated %s to <info>%s</info>', $moduleName, $moduleVersion));
50
-				}
51
-			}
52
-			return $this->restartScript($input, $output);
53
-		}
54
-		return 0;
55
-	}
36
+    /**
37
+     * {@inheritdoc}
38
+     */
39
+    protected function execute(InputInterface $input, OutputInterface $output)
40
+    {
41
+        $module = new Module($input->getArgument('module'));
42
+        $modulesUpdated = null;
43
+        while ($module->update($modulesUpdated))
44
+        {
45
+            if (is_array($modulesUpdated))
46
+            {
47
+                foreach ($modulesUpdated as $moduleName => $moduleVersion)
48
+                {
49
+                    $output->writeln(sprintf('updated %s to <info>%s</info>', $moduleName, $moduleVersion));
50
+                }
51
+            }
52
+            return $this->restartScript($input, $output);
53
+        }
54
+        return 0;
55
+    }
56 56
 }
57 57
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/RemoveCommand.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -17,24 +17,24 @@
 block discarded – undo
17 17
  */
18 18
 class RemoveCommand extends ModuleCommand
19 19
 {
20
-	/**
21
-	 * {@inheritdoc}
22
-	 */
23
-	protected function configure()
24
-	{
25
-		parent::configure();
20
+    /**
21
+     * {@inheritdoc}
22
+     */
23
+    protected function configure()
24
+    {
25
+        parent::configure();
26 26
 
27
-		$this->setName('module:remove')
28
-			->setDescription('Uninstall and remove module folder from system');
29
-	}
27
+        $this->setName('module:remove')
28
+            ->setDescription('Uninstall and remove module folder from system');
29
+    }
30 30
 
31
-	/**
32
-	 * {@inheritdoc}
33
-	 */
34
-	protected function execute(InputInterface $input, OutputInterface $output)
35
-	{
36
-		$module = new Module($input->getArgument('module'));
37
-		$module->remove();
38
-		$output->writeln(sprintf('removed <info>%s</info>', $module->getName()));
39
-	}
31
+    /**
32
+     * {@inheritdoc}
33
+     */
34
+    protected function execute(InputInterface $input, OutputInterface $output)
35
+    {
36
+        $module = new Module($input->getArgument('module'));
37
+        $module->remove();
38
+        $output->writeln(sprintf('removed <info>%s</info>', $module->getName()));
39
+    }
40 40
 }
41 41
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Module.php 1 patch
Indentation   +391 added lines, -391 removed lines patch added patch discarded remove patch
@@ -18,395 +18,395 @@
 block discarded – undo
18 18
  */
19 19
 class Module
20 20
 {
21
-	/** @var string */
22
-	private $name;
23
-
24
-	/** @var \CModule */
25
-	private $object;
26
-
27
-	/** @var bool */
28
-	private $beta = false;
29
-
30
-	/**
31
-	 * @param string $moduleName
32
-	 */
33
-	public function __construct($moduleName)
34
-	{
35
-		$this->name = $this->normalizeName($moduleName);
36
-	}
37
-
38
-	/**
39
-	 * @param string $moduleName
40
-	 * @return string
41
-	 */
42
-	protected function normalizeName($moduleName)
43
-	{
44
-		return preg_replace("/[^a-zA-Z0-9_.]+/i", "", trim($moduleName));
45
-	}
46
-
47
-	/**
48
-	 * @return \CModule
49
-	 */
50
-	protected function &getObject()
51
-	{
52
-		if (!isset($this->object))
53
-		{
54
-			$this->object = \CModule::CreateModuleObject($this->name);
55
-		}
56
-
57
-		if (!is_object($this->object) || !($this->object instanceof \CModule))
58
-		{
59
-			unset($this->object);
60
-			throw new Exception\ModuleNotFoundException('Module not found or incorrect', $this->name);
61
-		}
62
-
63
-		return $this->object;
64
-	}
65
-
66
-	/**
67
-	 * Checks for module and module object existence
68
-	 *
69
-	 * @return bool
70
-	 */
71
-	public function exist()
72
-	{
73
-		try
74
-		{
75
-			$this->getObject();
76
-		}
77
-		catch (Exception\ModuleNotFoundException $e)
78
-		{
79
-			return false;
80
-		}
81
-
82
-		return true;
83
-	}
84
-
85
-	/**
86
-	 * Check if module exists and installed
87
-	 *
88
-	 * @return bool
89
-	 */
90
-	public function isRegistered()
91
-	{
92
-		return ModuleManager::isModuleInstalled($this->name) && $this->exist();
93
-	}
94
-
95
-	/**
96
-	 * @return bool true for marketplace modules, false for kernel modules
97
-	 */
98
-	public function isThirdParty()
99
-	{
100
-		return strpos($this->name, '.') !== false;
101
-	}
102
-
103
-	/**
104
-	 * Install module
105
-	 *
106
-	 * @throws Exception\ModuleException
107
-	 * @throws BitrixException
108
-	 */
109
-	public function register()
110
-	{
111
-		if (!$this->isRegistered())
112
-		{
113
-			$moduleObject =& $this->getObject();
114
-
115
-			/**
116
-			 * It's important to check if module class defines InstallDB method (it must register module)
117
-			 * Thus absent InstallDB indicates that the module does not support automatic installation
118
-			 */
119
-			if ((new \ReflectionClass($moduleObject))->getMethod('InstallDB')->class !== get_class($moduleObject))
120
-			{
121
-				throw new Exception\ModuleInstallException(
122
-					'Missing InstallDB method. This module does not support automatic installation',
123
-					$this->name
124
-				);
125
-			}
126
-
127
-			if (!$moduleObject->InstallDB() && BitrixException::hasException())
128
-			{
129
-				throw new Exception\ModuleInstallException(
130
-					get_class($moduleObject) . '::InstallDB() returned false',
131
-					$this->name
132
-				);
133
-			}
134
-
135
-			$moduleObject->InstallEvents();
136
-
137
-			/** @noinspection PhpVoidFunctionResultUsedInspection */
138
-			if (!$moduleObject->InstallFiles() && BitrixException::hasException())
139
-			{
140
-				throw new Exception\ModuleInstallException(
141
-					get_class($moduleObject) . '::InstallFiles() returned false',
142
-					$this->name
143
-				);
144
-			}
145
-
146
-			if (!$this->isRegistered())
147
-			{
148
-				throw new Exception\ModuleInstallException(
149
-					'Module was not registered. Probably it does not support automatic installation.',
150
-					$this->name
151
-				);
152
-			}
153
-		}
154
-
155
-		return $this;
156
-	}
157
-
158
-	/**
159
-	 * Download module from marketplace
160
-	 *
161
-	 * @return $this
162
-	 */
163
-	public function load()
164
-	{
165
-		if (!$this->isRegistered())
166
-		{
167
-			if (!$this->exist())
168
-			{
169
-				require_once($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/classes/general/update_client_partner.php');
170
-
171
-				if (!\CUpdateClientPartner::LoadModuleNoDemand(
172
-					$this->getName(),
173
-					$strError,
174
-					$this->isBeta() ? 'N' : 'Y',
175
-					LANGUAGE_ID)
176
-				)
177
-				{
178
-					throw new Exception\ModuleLoadException($strError, $this->getName());
179
-				}
180
-			}
181
-		}
182
-
183
-		return $this;
184
-	}
185
-
186
-	/**
187
-	 * Uninstall module
188
-	 *
189
-	 * @throws Exception\ModuleException
190
-	 * @throws BitrixException
191
-	 */
192
-	public function unRegister()
193
-	{
194
-		$moduleObject = $this->getObject();
195
-
196
-		if ($this->isRegistered())
197
-		{
198
-			/**
199
-			 * It's important to check if module class defines UnInstallDB method (it should unregister module)
200
-			 * Thus absent UnInstallDB indicates that the module does not support automatic uninstallation
201
-			 */
202
-			if ((new \ReflectionClass($moduleObject))->getMethod('UnInstallDB')->class !== get_class($moduleObject))
203
-			{
204
-				throw new Exception\ModuleUninstallException(
205
-					'Missing UnInstallDB method. This module does not support automatic uninstallation',
206
-					$this->name
207
-				);
208
-			}
209
-
210
-			/** @noinspection PhpVoidFunctionResultUsedInspection */
211
-			if (!$moduleObject->UnInstallFiles() && BitrixException::hasException())
212
-			{
213
-				throw new Exception\ModuleUninstallException(
214
-					get_class($moduleObject) . '::UnInstallFiles() returned false',
215
-					$this->name
216
-				);
217
-			}
218
-
219
-			$moduleObject->UnInstallEvents();
220
-
221
-			/** @noinspection PhpVoidFunctionResultUsedInspection */
222
-			if (!$moduleObject->UnInstallDB() && BitrixException::hasException())
223
-			{
224
-				throw new Exception\ModuleUninstallException(
225
-					get_class($moduleObject) . '::UnInstallFiles() returned false',
226
-					$this->name
227
-				);
228
-			}
229
-
230
-			if ($this->isRegistered())
231
-			{
232
-				throw new Exception\ModuleUninstallException('Module was not unregistered', $this->name);
233
-			}
234
-		}
235
-
236
-		return $this;
237
-	}
238
-
239
-	/**
240
-	 * Uninstall and remove module directory
241
-	 */
242
-	public function remove()
243
-	{
244
-		if ($this->isRegistered())
245
-		{
246
-			$this->unRegister();
247
-		}
248
-
249
-		$path = getLocalPath('modules/' . $this->getName());
250
-
251
-		if ($path)
252
-		{
253
-			(new Filesystem())->remove($_SERVER['DOCUMENT_ROOT'] . $path);
254
-		}
255
-
256
-		unset($this->object);
257
-
258
-		return $this;
259
-	}
260
-
261
-	/**
262
-	 * Update module
263
-	 *
264
-	 * It must be called repeatedly until the method returns false.
265
-	 * After each call php must be restarted (new process created) to update module class and function definitions.
266
-	 *
267
-	 * @param array $modulesUpdated [optional]
268
-	 * @return bool
269
-	 */
270
-	public function update(&$modulesUpdated = null)
271
-	{
272
-		require_once($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/classes/general/update_client_partner.php');
273
-
274
-		if (!$this->isThirdParty())
275
-		{
276
-			throw new Exception\ModuleUpdateException('Kernel module updates are currently not supported.', $this->getName());
277
-		}
278
-
279
-		// ensures module existence
280
-		$this->getObject();
281
-
282
-		$errorMessage = $updateDescription = null;
283
-		$loadResult = \CUpdateClientPartner::LoadModulesUpdates(
284
-			$errorMessage,
285
-			$updateDescription,
286
-			LANGUAGE_ID,
287
-			$this->isBeta() ? 'N' : 'Y',
288
-			[$this->getName()],
289
-			true
290
-		);
291
-		switch ($loadResult)
292
-		{
293
-			// archive loaded
294
-			case "S":
295
-				return $this->update($modulesUpdated);
296
-
297
-			// error
298
-			case "E":
299
-				throw new Exception\ModuleUpdateException($errorMessage, $this->getName());
300
-
301
-			// finished installing updates
302
-			case "F":
303
-				return false;
304
-
305
-			// need to process loaded update
306
-			case 'U':
307
-				break;
308
-		}
309
-
310
-		/** @var string Temp directory with update files */
311
-		$updateDir = null;
312
-
313
-		if (!\CUpdateClientPartner::UnGzipArchive($updateDir, $errorMessage, true))
314
-		{
315
-			throw new Exception\ModuleUpdateException('[CL02] UnGzipArchive failed. ' . $errorMessage, $this->getName());
316
-		}
317
-
318
-		$this->validateUpdate($updateDir);
319
-
320
-		if (isset($updateDescription["DATA"]["#"]["NOUPDATES"]))
321
-		{
322
-			\CUpdateClientPartner::ClearUpdateFolder($_SERVER["DOCUMENT_ROOT"] . "/bitrix/updates/" . $updateDir);
323
-			return false;
324
-		}
325
-
326
-		$modulesUpdated = $updateDescr = [];
327
-		if (isset($updateDescription["DATA"]["#"]["ITEM"]))
328
-		{
329
-			foreach ($updateDescription["DATA"]["#"]["ITEM"] as $moduleInfo)
330
-			{
331
-				$modulesUpdated[$moduleInfo["@"]["NAME"]] = $moduleInfo["@"]["VALUE"];
332
-				$updateDescr[$moduleInfo["@"]["NAME"]] = $moduleInfo["@"]["DESCR"];
333
-			}
334
-		}
335
-
336
-		if (\CUpdateClientPartner::UpdateStepModules($updateDir, $errorMessage))
337
-		{
338
-			foreach ($modulesUpdated as $key => $value)
339
-			{
340
-				if (Option::set('main', 'event_log_marketplace', "Y") === "Y")
341
-				{
342
-					\CEventLog::Log("INFO", "MP_MODULE_DOWNLOADED", "main", $key, $value);
343
-				}
344
-			}
345
-		}
346
-		else
347
-		{
348
-			throw new Exception\ModuleUpdateException('[CL04] UpdateStepModules failed. ' . $errorMessage, $this->getName());
349
-		}
350
-
351
-		return true;
352
-	}
353
-
354
-	/**
355
-	 * Check update files
356
-	 * 
357
-	 * @param string $updateDir
358
-	 */
359
-	protected function validateUpdate($updateDir)
360
-	{
361
-		$errorMessage = null;
362
-		if (!\CUpdateClientPartner::CheckUpdatability($updateDir, $errorMessage))
363
-		{
364
-			throw new Exception\ModuleUpdateException('[CL03] CheckUpdatability failed. ' . $errorMessage, $this->getName());
365
-		}
366
-
367
-		if (isset($updateDescription["DATA"]["#"]["ERROR"]))
368
-		{
369
-			$errorMessage = "";
370
-			foreach ($updateDescription["DATA"]["#"]["ERROR"] as $errorDescription)
371
-			{
372
-				$errorMessage .= "[" . $errorDescription["@"]["TYPE"] . "] " . $errorDescription["#"];
373
-			}
374
-			throw new Exception\ModuleUpdateException($errorMessage, $this->getName());
375
-		}
376
-	}
377
-
378
-	/**
379
-	 * Returns module name
380
-	 *
381
-	 * @return string
382
-	 */
383
-	public function getName()
384
-	{
385
-		return $this->name;
386
-	}
387
-
388
-	/**
389
-	 * Beta releases allowed?
390
-	 *
391
-	 * @return boolean
392
-	 */
393
-	public function isBeta()
394
-	{
395
-		return $this->beta;
396
-	}
397
-
398
-	/**
399
-	 * Set beta releases installation
400
-	 *
401
-	 * @param boolean $beta
402
-	 */
403
-	public function setBeta($beta = true)
404
-	{
405
-		$this->beta = $beta;
406
-	}
407
-
408
-	public function getVersion()
409
-	{
410
-		return $this->getObject()->MODULE_VERSION;
411
-	}
21
+    /** @var string */
22
+    private $name;
23
+
24
+    /** @var \CModule */
25
+    private $object;
26
+
27
+    /** @var bool */
28
+    private $beta = false;
29
+
30
+    /**
31
+     * @param string $moduleName
32
+     */
33
+    public function __construct($moduleName)
34
+    {
35
+        $this->name = $this->normalizeName($moduleName);
36
+    }
37
+
38
+    /**
39
+     * @param string $moduleName
40
+     * @return string
41
+     */
42
+    protected function normalizeName($moduleName)
43
+    {
44
+        return preg_replace("/[^a-zA-Z0-9_.]+/i", "", trim($moduleName));
45
+    }
46
+
47
+    /**
48
+     * @return \CModule
49
+     */
50
+    protected function &getObject()
51
+    {
52
+        if (!isset($this->object))
53
+        {
54
+            $this->object = \CModule::CreateModuleObject($this->name);
55
+        }
56
+
57
+        if (!is_object($this->object) || !($this->object instanceof \CModule))
58
+        {
59
+            unset($this->object);
60
+            throw new Exception\ModuleNotFoundException('Module not found or incorrect', $this->name);
61
+        }
62
+
63
+        return $this->object;
64
+    }
65
+
66
+    /**
67
+     * Checks for module and module object existence
68
+     *
69
+     * @return bool
70
+     */
71
+    public function exist()
72
+    {
73
+        try
74
+        {
75
+            $this->getObject();
76
+        }
77
+        catch (Exception\ModuleNotFoundException $e)
78
+        {
79
+            return false;
80
+        }
81
+
82
+        return true;
83
+    }
84
+
85
+    /**
86
+     * Check if module exists and installed
87
+     *
88
+     * @return bool
89
+     */
90
+    public function isRegistered()
91
+    {
92
+        return ModuleManager::isModuleInstalled($this->name) && $this->exist();
93
+    }
94
+
95
+    /**
96
+     * @return bool true for marketplace modules, false for kernel modules
97
+     */
98
+    public function isThirdParty()
99
+    {
100
+        return strpos($this->name, '.') !== false;
101
+    }
102
+
103
+    /**
104
+     * Install module
105
+     *
106
+     * @throws Exception\ModuleException
107
+     * @throws BitrixException
108
+     */
109
+    public function register()
110
+    {
111
+        if (!$this->isRegistered())
112
+        {
113
+            $moduleObject =& $this->getObject();
114
+
115
+            /**
116
+             * It's important to check if module class defines InstallDB method (it must register module)
117
+             * Thus absent InstallDB indicates that the module does not support automatic installation
118
+             */
119
+            if ((new \ReflectionClass($moduleObject))->getMethod('InstallDB')->class !== get_class($moduleObject))
120
+            {
121
+                throw new Exception\ModuleInstallException(
122
+                    'Missing InstallDB method. This module does not support automatic installation',
123
+                    $this->name
124
+                );
125
+            }
126
+
127
+            if (!$moduleObject->InstallDB() && BitrixException::hasException())
128
+            {
129
+                throw new Exception\ModuleInstallException(
130
+                    get_class($moduleObject) . '::InstallDB() returned false',
131
+                    $this->name
132
+                );
133
+            }
134
+
135
+            $moduleObject->InstallEvents();
136
+
137
+            /** @noinspection PhpVoidFunctionResultUsedInspection */
138
+            if (!$moduleObject->InstallFiles() && BitrixException::hasException())
139
+            {
140
+                throw new Exception\ModuleInstallException(
141
+                    get_class($moduleObject) . '::InstallFiles() returned false',
142
+                    $this->name
143
+                );
144
+            }
145
+
146
+            if (!$this->isRegistered())
147
+            {
148
+                throw new Exception\ModuleInstallException(
149
+                    'Module was not registered. Probably it does not support automatic installation.',
150
+                    $this->name
151
+                );
152
+            }
153
+        }
154
+
155
+        return $this;
156
+    }
157
+
158
+    /**
159
+     * Download module from marketplace
160
+     *
161
+     * @return $this
162
+     */
163
+    public function load()
164
+    {
165
+        if (!$this->isRegistered())
166
+        {
167
+            if (!$this->exist())
168
+            {
169
+                require_once($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/classes/general/update_client_partner.php');
170
+
171
+                if (!\CUpdateClientPartner::LoadModuleNoDemand(
172
+                    $this->getName(),
173
+                    $strError,
174
+                    $this->isBeta() ? 'N' : 'Y',
175
+                    LANGUAGE_ID)
176
+                )
177
+                {
178
+                    throw new Exception\ModuleLoadException($strError, $this->getName());
179
+                }
180
+            }
181
+        }
182
+
183
+        return $this;
184
+    }
185
+
186
+    /**
187
+     * Uninstall module
188
+     *
189
+     * @throws Exception\ModuleException
190
+     * @throws BitrixException
191
+     */
192
+    public function unRegister()
193
+    {
194
+        $moduleObject = $this->getObject();
195
+
196
+        if ($this->isRegistered())
197
+        {
198
+            /**
199
+             * It's important to check if module class defines UnInstallDB method (it should unregister module)
200
+             * Thus absent UnInstallDB indicates that the module does not support automatic uninstallation
201
+             */
202
+            if ((new \ReflectionClass($moduleObject))->getMethod('UnInstallDB')->class !== get_class($moduleObject))
203
+            {
204
+                throw new Exception\ModuleUninstallException(
205
+                    'Missing UnInstallDB method. This module does not support automatic uninstallation',
206
+                    $this->name
207
+                );
208
+            }
209
+
210
+            /** @noinspection PhpVoidFunctionResultUsedInspection */
211
+            if (!$moduleObject->UnInstallFiles() && BitrixException::hasException())
212
+            {
213
+                throw new Exception\ModuleUninstallException(
214
+                    get_class($moduleObject) . '::UnInstallFiles() returned false',
215
+                    $this->name
216
+                );
217
+            }
218
+
219
+            $moduleObject->UnInstallEvents();
220
+
221
+            /** @noinspection PhpVoidFunctionResultUsedInspection */
222
+            if (!$moduleObject->UnInstallDB() && BitrixException::hasException())
223
+            {
224
+                throw new Exception\ModuleUninstallException(
225
+                    get_class($moduleObject) . '::UnInstallFiles() returned false',
226
+                    $this->name
227
+                );
228
+            }
229
+
230
+            if ($this->isRegistered())
231
+            {
232
+                throw new Exception\ModuleUninstallException('Module was not unregistered', $this->name);
233
+            }
234
+        }
235
+
236
+        return $this;
237
+    }
238
+
239
+    /**
240
+     * Uninstall and remove module directory
241
+     */
242
+    public function remove()
243
+    {
244
+        if ($this->isRegistered())
245
+        {
246
+            $this->unRegister();
247
+        }
248
+
249
+        $path = getLocalPath('modules/' . $this->getName());
250
+
251
+        if ($path)
252
+        {
253
+            (new Filesystem())->remove($_SERVER['DOCUMENT_ROOT'] . $path);
254
+        }
255
+
256
+        unset($this->object);
257
+
258
+        return $this;
259
+    }
260
+
261
+    /**
262
+     * Update module
263
+     *
264
+     * It must be called repeatedly until the method returns false.
265
+     * After each call php must be restarted (new process created) to update module class and function definitions.
266
+     *
267
+     * @param array $modulesUpdated [optional]
268
+     * @return bool
269
+     */
270
+    public function update(&$modulesUpdated = null)
271
+    {
272
+        require_once($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/classes/general/update_client_partner.php');
273
+
274
+        if (!$this->isThirdParty())
275
+        {
276
+            throw new Exception\ModuleUpdateException('Kernel module updates are currently not supported.', $this->getName());
277
+        }
278
+
279
+        // ensures module existence
280
+        $this->getObject();
281
+
282
+        $errorMessage = $updateDescription = null;
283
+        $loadResult = \CUpdateClientPartner::LoadModulesUpdates(
284
+            $errorMessage,
285
+            $updateDescription,
286
+            LANGUAGE_ID,
287
+            $this->isBeta() ? 'N' : 'Y',
288
+            [$this->getName()],
289
+            true
290
+        );
291
+        switch ($loadResult)
292
+        {
293
+            // archive loaded
294
+            case "S":
295
+                return $this->update($modulesUpdated);
296
+
297
+            // error
298
+            case "E":
299
+                throw new Exception\ModuleUpdateException($errorMessage, $this->getName());
300
+
301
+            // finished installing updates
302
+            case "F":
303
+                return false;
304
+
305
+            // need to process loaded update
306
+            case 'U':
307
+                break;
308
+        }
309
+
310
+        /** @var string Temp directory with update files */
311
+        $updateDir = null;
312
+
313
+        if (!\CUpdateClientPartner::UnGzipArchive($updateDir, $errorMessage, true))
314
+        {
315
+            throw new Exception\ModuleUpdateException('[CL02] UnGzipArchive failed. ' . $errorMessage, $this->getName());
316
+        }
317
+
318
+        $this->validateUpdate($updateDir);
319
+
320
+        if (isset($updateDescription["DATA"]["#"]["NOUPDATES"]))
321
+        {
322
+            \CUpdateClientPartner::ClearUpdateFolder($_SERVER["DOCUMENT_ROOT"] . "/bitrix/updates/" . $updateDir);
323
+            return false;
324
+        }
325
+
326
+        $modulesUpdated = $updateDescr = [];
327
+        if (isset($updateDescription["DATA"]["#"]["ITEM"]))
328
+        {
329
+            foreach ($updateDescription["DATA"]["#"]["ITEM"] as $moduleInfo)
330
+            {
331
+                $modulesUpdated[$moduleInfo["@"]["NAME"]] = $moduleInfo["@"]["VALUE"];
332
+                $updateDescr[$moduleInfo["@"]["NAME"]] = $moduleInfo["@"]["DESCR"];
333
+            }
334
+        }
335
+
336
+        if (\CUpdateClientPartner::UpdateStepModules($updateDir, $errorMessage))
337
+        {
338
+            foreach ($modulesUpdated as $key => $value)
339
+            {
340
+                if (Option::set('main', 'event_log_marketplace', "Y") === "Y")
341
+                {
342
+                    \CEventLog::Log("INFO", "MP_MODULE_DOWNLOADED", "main", $key, $value);
343
+                }
344
+            }
345
+        }
346
+        else
347
+        {
348
+            throw new Exception\ModuleUpdateException('[CL04] UpdateStepModules failed. ' . $errorMessage, $this->getName());
349
+        }
350
+
351
+        return true;
352
+    }
353
+
354
+    /**
355
+     * Check update files
356
+     * 
357
+     * @param string $updateDir
358
+     */
359
+    protected function validateUpdate($updateDir)
360
+    {
361
+        $errorMessage = null;
362
+        if (!\CUpdateClientPartner::CheckUpdatability($updateDir, $errorMessage))
363
+        {
364
+            throw new Exception\ModuleUpdateException('[CL03] CheckUpdatability failed. ' . $errorMessage, $this->getName());
365
+        }
366
+
367
+        if (isset($updateDescription["DATA"]["#"]["ERROR"]))
368
+        {
369
+            $errorMessage = "";
370
+            foreach ($updateDescription["DATA"]["#"]["ERROR"] as $errorDescription)
371
+            {
372
+                $errorMessage .= "[" . $errorDescription["@"]["TYPE"] . "] " . $errorDescription["#"];
373
+            }
374
+            throw new Exception\ModuleUpdateException($errorMessage, $this->getName());
375
+        }
376
+    }
377
+
378
+    /**
379
+     * Returns module name
380
+     *
381
+     * @return string
382
+     */
383
+    public function getName()
384
+    {
385
+        return $this->name;
386
+    }
387
+
388
+    /**
389
+     * Beta releases allowed?
390
+     *
391
+     * @return boolean
392
+     */
393
+    public function isBeta()
394
+    {
395
+        return $this->beta;
396
+    }
397
+
398
+    /**
399
+     * Set beta releases installation
400
+     *
401
+     * @param boolean $beta
402
+     */
403
+    public function setBeta($beta = true)
404
+    {
405
+        $this->beta = $beta;
406
+    }
407
+
408
+    public function getVersion()
409
+    {
410
+        return $this->getObject()->MODULE_VERSION;
411
+    }
412 412
 }
413 413
\ No newline at end of file
Please login to merge, or discard this patch.
src/Module/Command/ModuleCommand.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -21,48 +21,48 @@
 block discarded – undo
21 21
  */
22 22
 abstract class ModuleCommand extends BitrixCommand
23 23
 {
24
-	/**
25
-	 * {@inheritdoc}
26
-	 */
27
-	protected function configure()
28
-	{
29
-		parent::configure();
24
+    /**
25
+     * {@inheritdoc}
26
+     */
27
+    protected function configure()
28
+    {
29
+        parent::configure();
30 30
 
31
-		$this->addArgument('module', InputArgument::REQUIRED, 'Module name (e.g. `vendor.module`)')
32
-			->addOption('confirm-thirdparty', 'ct', InputOption::VALUE_NONE, 'Suppress third-party modules warning');
33
-	}
31
+        $this->addArgument('module', InputArgument::REQUIRED, 'Module name (e.g. `vendor.module`)')
32
+            ->addOption('confirm-thirdparty', 'ct', InputOption::VALUE_NONE, 'Suppress third-party modules warning');
33
+    }
34 34
 
35
-	/**
36
-	 * @inheritdoc
37
-	 */
38
-	protected function interact(InputInterface $input, OutputInterface $output)
39
-	{
40
-		parent::interact($input, $output);
35
+    /**
36
+     * @inheritdoc
37
+     */
38
+    protected function interact(InputInterface $input, OutputInterface $output)
39
+    {
40
+        parent::interact($input, $output);
41 41
 
42
-		$module = new Module($input->getArgument('module'));
42
+        $module = new Module($input->getArgument('module'));
43 43
 
44
-		if (in_array($this->getName(), ['module:register', 'module:unregister'])
45
-			&& $module->isThirdParty() && !$input->getOption('confirm-thirdparty')
46
-		)
47
-		{
48
-			$output->writeln($module->isThirdParty() . ' is not a kernel module. Correct operation cannot be guaranteed for third-party modules!');
49
-		}
50
-	}
44
+        if (in_array($this->getName(), ['module:register', 'module:unregister'])
45
+            && $module->isThirdParty() && !$input->getOption('confirm-thirdparty')
46
+        )
47
+        {
48
+            $output->writeln($module->isThirdParty() . ' is not a kernel module. Correct operation cannot be guaranteed for third-party modules!');
49
+        }
50
+    }
51 51
 
52
-	/**
53
-	 * Gets console commands from this package.
54
-	 *
55
-	 * @return Command[]
56
-	 */
57
-	public static function getCommands()
58
-	{
59
-		return [
60
-			new LoadCommand(),
61
-			new RegisterCommand(),
62
-			new RemoveCommand(),
63
-			new UnregisterCommand(),
64
-			new UpdateCommand(),
65
-		];
66
-	}
52
+    /**
53
+     * Gets console commands from this package.
54
+     *
55
+     * @return Command[]
56
+     */
57
+    public static function getCommands()
58
+    {
59
+        return [
60
+            new LoadCommand(),
61
+            new RegisterCommand(),
62
+            new RemoveCommand(),
63
+            new UnregisterCommand(),
64
+            new UpdateCommand(),
65
+        ];
66
+    }
67 67
 
68 68
 }
69 69
\ No newline at end of file
Please login to merge, or discard this patch.