Failed Conditions
Push — master ( ba48ab...48c00e )
by Alexander
02:35
created

RevisionLog::_databaseReady()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * This file is part of the SVN-Buddy library.
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 *
7
 * @copyright Alexander Obuhovich <[email protected]>
8
 * @link      https://github.com/console-helpers/svn-buddy
9
 */
10
11
namespace ConsoleHelpers\SVNBuddy\Repository\RevisionLog;
12
13
14
use ConsoleHelpers\ConsoleKit\ConsoleIO;
15
use ConsoleHelpers\SVNBuddy\Repository\Connector\Connector;
16
use ConsoleHelpers\SVNBuddy\Repository\RevisionLog\Plugin\DatabaseCollectorPlugin\IDatabaseCollectorPlugin;
17
use ConsoleHelpers\SVNBuddy\Repository\RevisionLog\Plugin\IOverwriteAwarePlugin;
18
use ConsoleHelpers\SVNBuddy\Repository\RevisionLog\Plugin\IPlugin;
19
use ConsoleHelpers\SVNBuddy\Repository\RevisionLog\Plugin\RepositoryCollectorPlugin\IRepositoryCollectorPlugin;
20
use ConsoleHelpers\SVNBuddy\Repository\RevisionUrlBuilder;
21
22
class RevisionLog
23
{
24
25
	const FLAG_VERBOSE = 1;
26
27
	const FLAG_MERGE_HISTORY = 2;
28
29
	/**
30
	 * Repository path.
31
	 *
32
	 * @var string
33
	 */
34
	private $_repositoryRootUrl;
35
36
	/**
37
	 * Project path.
38
	 *
39
	 * @var string
40
	 */
41
	private $_projectPath;
42
43
	/**
44
	 * Ref name.
45
	 *
46
	 * @var string
47
	 */
48
	private $_refName;
49
50
	/**
51
	 * Repository connector.
52
	 *
53
	 * @var Connector
54
	 */
55
	private $_repositoryConnector;
56
57
	/**
58
	 * Console IO.
59
	 *
60
	 * @var ConsoleIO
61
	 */
62
	private $_io;
63
64
	/**
65
	 * Installed plugins.
66
	 *
67
	 * @var IPlugin[]
68
	 */
69
	private $_plugins = array();
70
71
	/**
72
	 * Revision URL builder.
73
	 *
74
	 * @var RevisionUrlBuilder
75
	 */
76
	private $_revisionUrlBuilder;
77
78
	/**
79
	 * Force refresh flag filename.
80
	 *
81
	 * @var string
82
	 */
83
	private $_forceRefreshFlagFilename;
84
85
	/**
86
	 * Create revision log.
87
	 *
88
	 * @param string             $repository_url       Repository url.
89
	 * @param RevisionUrlBuilder $revision_url_builder Revision URL builder.
90
	 * @param Connector          $repository_connector Repository connector.
91
	 * @param string             $working_directory    Working directory.
92
	 * @param ConsoleIO          $io                   Console IO.
93
	 */
94 19
	public function __construct(
95
		$repository_url,
96
		RevisionUrlBuilder $revision_url_builder,
97
		Connector $repository_connector,
98
		$working_directory,
99
		ConsoleIO $io = null
100
	) {
101 19
		$this->_io = $io;
102 19
		$this->_repositoryConnector = $repository_connector;
103
104 19
		$this->_repositoryRootUrl = $repository_connector->getRootUrl($repository_url);
105
106 19
		$relative_path = $repository_connector->getRelativePath($repository_url);
107 19
		$this->_projectPath = $repository_connector->getProjectUrl($relative_path) . '/';
108 19
		$this->_refName = $repository_connector->getRefByPath($relative_path);
0 ignored issues
show
Documentation Bug introduced by
It seems like $repository_connector->g...fByPath($relative_path) can also be of type boolean. However, the property $_refName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
109 19
		$this->_revisionUrlBuilder = $revision_url_builder;
110 19
		$this->_forceRefreshFlagFilename = $working_directory . '/' . md5($this->_repositoryRootUrl) . '.force-refresh';
111
	}
112
113
	/**
114
	 * Returns revision URL builder.
115
	 *
116
	 * @return RevisionUrlBuilder
117
	 */
118 1
	public function getRevisionURLBuilder()
119
	{
120 1
		return $this->_revisionUrlBuilder;
121
	}
122
123
	/**
124
	 * Queries missing revisions.
125
	 *
126
	 * @param boolean $is_migration Is migration.
127
	 *
128
	 * @return void
129
	 * @throws \LogicException When no plugins are registered.
130
	 */
131 6
	public function refresh($is_migration)
132
	{
133 6
		if ( !$this->_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_plugins of type ConsoleHelpers\SVNBuddy\...ionLog\Plugin\IPlugin[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
134 1
			throw new \LogicException('Please register at least one revision log plugin.');
135
		}
136
137 5
		$this->_databaseReady();
138
139 5
		if ( $is_migration ) {
140
			// Import missing data for imported commits only.
141
			$from_revision = 0;
142
			$to_revision = $this->_getAggregateRevision('max');
143
		}
144
		else {
145
			// Import all data for new commits only.
146 5
			$from_revision = $this->_getAggregateRevision('min');
147
148 5
			if ( $this->getForceRefreshFlag() ) {
149
				$this->_repositoryConnector->withCacheOverwrite(true);
150
				$this->setForceRefreshFlag(false);
151
			}
152
153 5
			$to_revision = $this->_repositoryConnector->getLastRevision($this->_repositoryRootUrl);
154
		}
155
156 5
		if ( $to_revision > $from_revision ) {
157 3
			$this->_queryRevisionData($from_revision, $to_revision);
158
		}
159
	}
160
161
	/**
162
	 * Sets force refresh flag.
163
	 *
164
	 * @param boolean $flag Flag.
165
	 *
166
	 * @return void
167
	 */
168
	public function setForceRefreshFlag($flag)
169
	{
170
		if ( $flag ) {
171
			touch($this->_forceRefreshFlagFilename);
172
		}
173
		else {
174
			unlink($this->_forceRefreshFlagFilename);
175
		}
176
	}
177
178
	/**
179
	 * Gets force refresh flag.
180
	 *
181
	 * @return boolean
182
	 */
183 5
	protected function getForceRefreshFlag()
184
	{
185 5
		return file_exists($this->_forceRefreshFlagFilename);
186
	}
187
188
	/**
189
	 * Reparses a revision.
190
	 *
191
	 * @param integer $revision Revision.
192
	 *
193
	 * @return void
194
	 * @throws \LogicException When no plugins are registered.
195
	 */
196
	public function reparse($revision)
197
	{
198
		if ( !$this->_plugins ) {
199
			throw new \LogicException('Please register at least one revision log plugin.');
200
		}
201
202
		$this->_databaseReady();
203
		$this->_queryRevisionData($revision, $revision, true);
204
	}
205
206
	/**
207
	 * Reports to each plugin, that database is ready for usage.
208
	 *
209
	 * @return void
210
	 */
211 5
	private function _databaseReady()
212
	{
213 5
		foreach ( $this->_plugins as $plugin ) {
214 5
			$plugin->whenDatabaseReady();
215
		}
216
	}
217
218
	/**
219
	 * Returns aggregated revision from all plugins.
220
	 *
221
	 * @param string $function Aggregate function.
222
	 *
223
	 * @return integer
224
	 */
225 5
	private function _getAggregateRevision($function)
226
	{
227 5
		$last_revisions = array();
228
229 5
		foreach ( $this->_plugins as $plugin ) {
230 5
			$last_revisions[] = $plugin->getLastRevision();
231
		}
232
233 5
		if ( count($last_revisions) > 1 ) {
234 5
			return call_user_func_array($function, $last_revisions);
235
		}
236
237
		return current($last_revisions);
238
	}
239
240
	/**
241
	 * Queries missing revision data.
242
	 *
243
	 * @param integer $from_revision From revision.
244
	 * @param integer $to_revision   To revision.
245
	 * @param boolean $overwrite     Overwrite.
246
	 *
247
	 * @return void
248
	 */
249 3
	private function _queryRevisionData($from_revision, $to_revision, $overwrite = false)
250
	{
251 3
		$this->_useRepositoryCollectorPlugins($from_revision, $to_revision, $overwrite);
252 3
		$this->_useDatabaseCollectorPlugins($from_revision, $to_revision, $overwrite);
253
254 3
		if ( isset($this->_io) && $this->_io->isVerbose() ) {
255 1
			$this->_displayPluginActivityStatistics();
256
		}
257
	}
258
259
	/**
260
	 * Use repository collector plugins.
261
	 *
262
	 * @param integer $from_revision From revision.
263
	 * @param integer $to_revision   To revision.
264
	 * @param boolean $overwrite     Overwrite.
265
	 *
266
	 * @return void
267
	 */
268 3
	private function _useRepositoryCollectorPlugins($from_revision, $to_revision, $overwrite = false)
269
	{
270 3
		$batch_size = 500; // Revision count to query in one go.
271
272
		// The "io" isn't set during autocomplete.
273 3
		if ( isset($this->_io) ) {
274
			// Create progress bar for repository plugins, where data amount is known upfront.
275 2
			$progress_bar = $this->_io->createProgressBar(ceil(($to_revision - $from_revision) / $batch_size) + 1);
0 ignored issues
show
Bug introduced by
ceil($to_revision - $fro...sion / $batch_size) + 1 of type double is incompatible with the type integer expected by parameter $max of ConsoleHelpers\ConsoleKi...IO::createProgressBar(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

275
			$progress_bar = $this->_io->createProgressBar(/** @scrutinizer ignore-type */ ceil(($to_revision - $from_revision) / $batch_size) + 1);
Loading history...
276 2
			$progress_bar->setMessage(
277 2
				$overwrite ? '* Reparsing revisions:' : ' * Reading missing revisions:'
278 2
			);
279 2
			$progress_bar->setFormat(
280 2
				'%message% %current%/%max% [%bar%] <info>%percent:3s%%</info> %elapsed:6s%/%estimated:-6s% <info>%memory:-10s%</info>'
281 2
			);
282 2
			$progress_bar->start();
283
		}
284
285 3
		$plugins = $this->getRepositoryCollectorPlugins($overwrite);
286
287 3
		if ( $overwrite ) {
288
			$this->setPluginsOverwriteMode($plugins, true);
289
		}
290
291 3
		$range_start = $from_revision;
292 3
		$cache_duration = $overwrite ? null : '10 years';
293 3
		$log_command_arguments = $this->_getLogCommandArguments($plugins);
294
295 3
		while ( $range_start <= $to_revision ) {
296 3
			$range_end = min($range_start + ($batch_size - 1), $to_revision);
297
298 3
			$command_arguments = str_replace(
299 3
				array('{revision_range}', '{repository_url}'),
300 3
				array($range_start . ':' . $range_end, $this->_repositoryRootUrl),
301 3
				$log_command_arguments
302 3
			);
303 3
			$command = $this->_repositoryConnector->getCommand('log', $command_arguments);
304 3
			$command->setCacheDuration($cache_duration);
305 3
			$svn_log = $command->run();
306
307 3
			$this->_parseLog($svn_log, $plugins);
0 ignored issues
show
Bug introduced by
It seems like $svn_log can also be of type string; however, parameter $log of ConsoleHelpers\SVNBuddy\...evisionLog::_parseLog() does only seem to accept SimpleXMLElement, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

307
			$this->_parseLog(/** @scrutinizer ignore-type */ $svn_log, $plugins);
Loading history...
308
309 3
			$range_start = $range_end + 1;
310
311 3
			if ( isset($progress_bar) ) {
312 2
				$progress_bar->advance();
313
			}
314
		}
315
316
		// Remove progress bar of repository plugins.
317 3
		if ( isset($progress_bar) ) {
318 2
			$progress_bar->clear();
319 2
			unset($progress_bar);
320
		}
321
322 3
		if ( $overwrite ) {
323
			$this->setPluginsOverwriteMode($plugins, false);
324
		}
325
	}
326
327
	/**
328
	 * Use database collector plugins.
329
	 *
330
	 * @param integer $from_revision From revision.
331
	 * @param integer $to_revision   To revision.
332
	 * @param boolean $overwrite     Overwrite.
333
	 *
334
	 * @return void
335
	 */
336 3
	private function _useDatabaseCollectorPlugins($from_revision, $to_revision, $overwrite = false)
337
	{
338 3
		$plugins = $this->getDatabaseCollectorPlugins($overwrite);
339
340 3
		if ( $overwrite ) {
341
			$this->setPluginsOverwriteMode($plugins, true);
342
		}
343
344
		// The "io" isn't set during autocomplete.
345 3
		if ( isset($this->_io) ) {
346
			// Create progress bar for database plugins, where data amount isn't known upfront.
347 2
			$progress_bar = $this->_io->createProgressBar();
348 2
			$progress_bar->setMessage(
349 2
				$overwrite ? '* Reparsing revisions:' : ' * Reading missing revisions:'
350 2
			);
351 2
			$progress_bar->setFormat('%message% %current% [%bar%] %elapsed:6s% <info>%memory:-10s%</info>');
352 2
			$progress_bar->start();
353
354 2
			foreach ( $plugins as $plugin ) {
355 2
				$plugin->process($from_revision, $to_revision, $progress_bar);
356
			}
357
		}
358
		else {
359 1
			foreach ( $plugins as $plugin ) {
360 1
				$plugin->process($from_revision, $to_revision);
361
			}
362
		}
363
364 3
		if ( $overwrite ) {
365
			$this->setPluginsOverwriteMode($plugins, false);
366
		}
367
368 3
		if ( isset($progress_bar) ) {
369 2
			$progress_bar->finish();
370 2
			$this->_io->writeln('');
371
		}
372
	}
373
374
	/**
375
	 * Returns arguments for "log" command.
376
	 *
377
	 * @param IRepositoryCollectorPlugin[] $plugins Plugins.
378
	 *
379
	 * @return array
380
	 */
381 3
	private function _getLogCommandArguments(array $plugins)
382
	{
383 3
		$query_flags = $this->_getRevisionQueryFlags($plugins);
384
385 3
		$ret = array('-r', '{revision_range}', '--xml');
386
387 3
		if ( in_array(self::FLAG_VERBOSE, $query_flags) ) {
388 3
			$ret[] = '--verbose';
389
		}
390
391 3
		if ( in_array(self::FLAG_MERGE_HISTORY, $query_flags) ) {
392 3
			$ret[] = '--use-merge-history';
393
		}
394
395 3
		$ret[] = '{repository_url}';
396
397 3
		return $ret;
398
	}
399
400
	/**
401
	 * Returns revision query flags.
402
	 *
403
	 * @param IRepositoryCollectorPlugin[] $plugins Plugins.
404
	 *
405
	 * @return array
406
	 */
407 3
	private function _getRevisionQueryFlags(array $plugins)
408
	{
409 3
		$ret = array();
410
411 3
		foreach ( $plugins as $plugin ) {
412 3
			$ret = array_merge($ret, $plugin->getRevisionQueryFlags());
413
		}
414
415 3
		return array_unique($ret);
416
	}
417
418
	/**
419
	 * Parses output of "svn log" command.
420
	 *
421
	 * @param \SimpleXMLElement            $log     Log.
422
	 * @param IRepositoryCollectorPlugin[] $plugins Plugins.
423
	 *
424
	 * @return void
425
	 */
426 3
	private function _parseLog(\SimpleXMLElement $log, array $plugins)
427
	{
428 3
		foreach ( $plugins as $plugin ) {
429 3
			$plugin->parse($log);
430
		}
431
	}
432
433
	/**
434
	 * Displays plugin activity statistics.
435
	 *
436
	 * @return void
437
	 */
438 1
	private function _displayPluginActivityStatistics()
439
	{
440 1
		$statistics = array();
441
442
		// Combine statistics from all plugins.
443 1
		foreach ( $this->_plugins as $plugin ) {
444 1
			$statistics = array_merge($statistics, array_filter($plugin->getStatistics()));
445
		}
446
447
		// Show statistics.
448 1
		$this->_io->writeln('<debug>Combined Plugin Statistics:</debug>');
449
450 1
		foreach ( $statistics as $statistic_type => $occurrences ) {
451 1
			$this->_io->writeln('<debug> * ' . $statistic_type . ': ' . $occurrences . '</debug>');
452
		}
453
	}
454
455
	/**
456
	 * Registers a plugin.
457
	 *
458
	 * @param IPlugin $plugin Plugin.
459
	 *
460
	 * @return void
461
	 * @throws \LogicException When plugin is registered several times.
462
	 */
463 12
	public function registerPlugin(IPlugin $plugin)
464
	{
465 12
		$plugin_name = $plugin->getName();
466
467 12
		if ( $this->pluginRegistered($plugin_name) ) {
468 1
			throw new \LogicException('The "' . $plugin_name . '" revision log plugin is already registered.');
469
		}
470
471 12
		$plugin->setRevisionLog($this);
472 12
		$this->_plugins[$plugin_name] = $plugin;
473
	}
474
475
	/**
476
	 * Finds information using plugin.
477
	 *
478
	 * @param string       $plugin_name Plugin name.
479
	 * @param array|string $criteria    Search criteria.
480
	 *
481
	 * @return array
482
	 */
483 3
	public function find($plugin_name, $criteria)
484
	{
485 3
		return $this->getPlugin($plugin_name)->find((array)$criteria, $this->_projectPath);
486
	}
487
488
	/**
489
	 * Returns information about revisions.
490
	 *
491
	 * @param string $plugin_name Plugin name.
492
	 * @param array  $revisions   Revisions.
493
	 *
494
	 * @return array
495
	 */
496 3
	public function getRevisionsData($plugin_name, array $revisions)
497
	{
498 3
		return $this->getPlugin($plugin_name)->getRevisionsData($revisions);
499
	}
500
501
	/**
502
	 * Determines if plugin is registered.
503
	 *
504
	 * @param string $plugin_name Plugin name.
505
	 *
506
	 * @return boolean
507
	 */
508 15
	public function pluginRegistered($plugin_name)
509
	{
510 15
		return array_key_exists($plugin_name, $this->_plugins);
511
	}
512
513
	/**
514
	 * Returns plugin instance.
515
	 *
516
	 * @param string $plugin_name Plugin name.
517
	 *
518
	 * @return IPlugin
519
	 * @throws \InvalidArgumentException When unknown plugin is given.
520
	 */
521 8
	public function getPlugin($plugin_name)
522
	{
523 8
		if ( !$this->pluginRegistered($plugin_name) ) {
524 3
			throw new \InvalidArgumentException('The "' . $plugin_name . '" revision log plugin is unknown.');
525
		}
526
527 5
		return $this->_plugins[$plugin_name];
528
	}
529
530
	/**
531
	 * Returns bugs, from revisions.
532
	 *
533
	 * @param array $revisions Revisions.
534
	 *
535
	 * @return array
536
	 */
537 1
	public function getBugsFromRevisions(array $revisions)
538
	{
539 1
		$bugs = array();
540 1
		$revisions_bugs = $this->getRevisionsData('bugs', $revisions);
541
542 1
		foreach ( $revisions as $revision ) {
543 1
			$revision_bugs = $revisions_bugs[$revision];
544
545 1
			foreach ( $revision_bugs as $bug_id ) {
546 1
				$bugs[$bug_id] = true;
547
			}
548
		}
549
550 1
		return array_keys($bugs);
551
	}
552
553
	/**
554
	 * Returns repository collector plugins.
555
	 *
556
	 * @param boolean $overwrite_mode Overwrite mode.
557
	 *
558
	 * @return IRepositoryCollectorPlugin[]
559
	 */
560 3
	protected function getRepositoryCollectorPlugins($overwrite_mode)
561
	{
562 3
		$plugins = $this->getPluginsByInterface(IRepositoryCollectorPlugin::class);
563
564 3
		if ( !$overwrite_mode ) {
565 3
			return $plugins;
566
		}
567
568
		return $this->getPluginsByInterface(IOverwriteAwarePlugin::class, $plugins);
569
	}
570
571
	/**
572
	 * Returns database collector plugins.
573
	 *
574
	 * @param boolean $overwrite_mode Overwrite mode.
575
	 *
576
	 * @return IDatabaseCollectorPlugin[]
577
	 */
578 3
	protected function getDatabaseCollectorPlugins($overwrite_mode)
579
	{
580 3
		$plugins = $this->getPluginsByInterface(IDatabaseCollectorPlugin::class);
581
582 3
		if ( !$overwrite_mode ) {
583 3
			return $plugins;
584
		}
585
586
		return $this->getPluginsByInterface(IOverwriteAwarePlugin::class, $plugins);
587
	}
588
589
	/**
590
	 * Returns plugin list filtered by interface.
591
	 *
592
	 * @param string    $interface Interface name.
593
	 * @param IPlugin[] $plugins   Plugins.
594
	 *
595
	 * @return IPlugin[]
596
	 */
597 3
	protected function getPluginsByInterface($interface, array $plugins = array())
598
	{
599 3
		if ( !$plugins ) {
600 3
			$plugins = $this->_plugins;
601
		}
602
603 3
		$ret = array();
604
605 3
		foreach ( $plugins as $plugin ) {
606 3
			if ( $plugin instanceof $interface ) {
607 3
				$ret[] = $plugin;
608
			}
609
		}
610
611 3
		return $ret;
612
	}
613
614
	/**
615
	 * Sets overwrite mode.
616
	 *
617
	 * @param IOverwriteAwarePlugin[] $plugins        Plugins.
618
	 * @param boolean                 $overwrite_mode Overwrite mode.
619
	 *
620
	 * @return void
621
	 */
622
	protected function setPluginsOverwriteMode(array $plugins, $overwrite_mode)
623
	{
624
		foreach ( $plugins as $plugin ) {
625
			$plugin->setOverwriteMode($overwrite_mode);
626
		}
627
	}
628
629
	/**
630
	 * Returns project path.
631
	 *
632
	 * @return string
633
	 */
634 1
	public function getProjectPath()
635
	{
636 1
		return $this->_projectPath;
637
	}
638
639
	/**
640
	 * Returns ref name.
641
	 *
642
	 * @return string
643
	 */
644 1
	public function getRefName()
645
	{
646 1
		return $this->_refName;
647
	}
648
649
}
650