RevisionPrinter::printRevisions()   F
last analyzed

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 158
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 702

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 84
c 7
b 0
f 0
dl 0
loc 158
ccs 0
cts 90
cp 0
rs 0
cc 26
nc 442624
nop 3
crap 702

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\SVNBuddy\Helper\DateHelper;
15
use ConsoleHelpers\SVNBuddy\Helper\OutputHelper;
16
use Symfony\Component\Console\Helper\Table;
17
use Symfony\Component\Console\Helper\TableCell;
18
use Symfony\Component\Console\Helper\TableSeparator;
19
use Symfony\Component\Console\Output\OutputInterface;
20
21
class RevisionPrinter
22
{
23
24
	const COLUMN_FULL_MESSAGE = 1;
25
26
	const COLUMN_DETAILS = 2;
27
28
	const COLUMN_SUMMARY = 3;
29
30
	const COLUMN_REFS = 4;
31
32
	const COLUMN_MERGE_ORACLE = 5;
33
34
	const COLUMN_MERGE_STATUS = 6;
35
36
	/**
37
	 * Date helper.
38
	 *
39
	 * @var DateHelper
40
	 */
41
	private $_dateHelper;
42
43
	/**
44
	 * Output helper.
45
	 *
46
	 * @var OutputHelper
47
	 */
48
	private $_outputHelper;
49
50
	/**
51
	 * Columns.
52
	 *
53
	 * @var array
54
	 */
55
	private $_columns = array();
56
57
	/**
58
	 * Aggregate by bug.
59
	 *
60
	 * @var boolean
61
	 */
62
	private $_aggregateByBug = false;
63
64
	/**
65
	 * Merge conflict regexps.
66
	 *
67
	 * @var array
68
	 */
69
	private $_mergeConflictRegExps = array();
70
71
	/**
72
	 * Log message limit.
73
	 *
74
	 * @var integer
75
	 */
76
	private $_logMessageLimit = 68;
77
78
	/**
79
	 * Current revision (e.g. in a working copy).
80
	 *
81
	 * @var integer|null
82
	 */
83
	private $_currentRevision;
84
85
	/**
86
	 * Creates instance of revision printer.
87
	 *
88
	 * @param DateHelper   $date_helper   Date helper.
89
	 * @param OutputHelper $output_helper Output helper.
90
	 */
91 1
	public function __construct(DateHelper $date_helper, OutputHelper $output_helper)
92
	{
93 1
		$this->_dateHelper = $date_helper;
94 1
		$this->_outputHelper = $output_helper;
95
96 1
		$this->_resetState();
97
	}
98
99
	/**
100
	 * Resets state.
101
	 *
102
	 * @return void
103
	 */
104 1
	private function _resetState()
105
	{
106 1
		$this->_columns = array();
107 1
		$this->_mergeConflictRegExps = array();
108 1
		$this->_logMessageLimit = 68;
109 1
		$this->_aggregateByBug = false;
110
	}
111
112
	/**
113
	 * Adds column to the output.
114
	 *
115
	 * @param integer $column Column.
116
	 *
117
	 * @return self
118
	 */
119
	public function withColumn($column)
120
	{
121
		$this->_columns[] = $column;
122
123
		return $this;
124
	}
125
126
	/**
127
	 * Sets aggregate by bug.
128
	 *
129
	 * @param boolean $aggregate_by_bug Aggregate by bug.
130
	 *
131
	 * @return void
132
	 */
133
	public function setAggregateByBug($aggregate_by_bug)
134
	{
135
		$this->_aggregateByBug = $aggregate_by_bug;
136
	}
137
138
	/**
139
	 * Sets merge conflict regexps.
140
	 *
141
	 * @param array $merge_conflict_regexps Merge conflict regexps.
142
	 *
143
	 * @return void
144
	 */
145
	public function setMergeConflictRegExps(array $merge_conflict_regexps)
146
	{
147
		$this->_mergeConflictRegExps = $merge_conflict_regexps;
148
	}
149
150
	/**
151
	 * Sets log message limit.
152
	 *
153
	 * @param integer $log_message_limit Log message limit.
154
	 *
155
	 * @return void
156
	 */
157
	public function setLogMessageLimit($log_message_limit)
158
	{
159
		$this->_logMessageLimit = $log_message_limit;
160
	}
161
162
	/**
163
	 * Sets current revision.
164
	 *
165
	 * @param integer $revision Revision.
166
	 *
167
	 * @return void
168
	 */
169
	public function setCurrentRevision($revision)
170
	{
171
		$this->_currentRevision = $revision;
172
	}
173
174
	/**
175
	 * Prints revisions.
176
	 *
177
	 * @param RevisionLog     $revision_log Revision log.
178
	 * @param array           $revisions    Revisions.
179
	 * @param OutputInterface $output       Output.
180
	 *
181
	 * @return void
182
	 */
183
	public function printRevisions(RevisionLog $revision_log, array $revisions, OutputInterface $output)
184
	{
185
		$table = new Table($output);
186
		$headers = array('Revision', 'Author', 'Date', 'Bug-ID', 'Log Message');
187
188
		$with_full_message = in_array(self::COLUMN_FULL_MESSAGE, $this->_columns);
189
		$with_details = in_array(self::COLUMN_DETAILS, $this->_columns);
190
191
		// Add "Summary" header.
192
		$with_summary = in_array(self::COLUMN_SUMMARY, $this->_columns);
193
194
		if ( $with_summary ) {
195
			$headers[] = 'Summary';
196
		}
197
198
		// Add "Refs" header.
199
		$with_refs = in_array(self::COLUMN_REFS, $this->_columns);
200
201
		if ( $with_refs ) {
202
			$headers[] = 'Refs';
203
		}
204
205
		$with_merge_oracle = in_array(self::COLUMN_MERGE_ORACLE, $this->_columns);
206
207
		// Add "M.O." header.
208
		if ( $with_merge_oracle ) {
209
			$headers[] = 'M.O.';
210
		}
211
212
		// Add "Merged Via" header.
213
		$with_merge_status = in_array(self::COLUMN_MERGE_STATUS, $this->_columns);
214
215
		if ( $with_merge_status ) {
216
			$headers[] = 'Merged Via';
217
		}
218
219
		$table->setHeaders($headers);
220
221
		$prev_bugs = null;
222
		$last_bug_color = 'yellow';
223
224
		if ( $this->_aggregateByBug ) {
225
			$aggregated_revisions = $this->aggregateRevisionsByBug($revisions, $revision_log);
226
			$revisions = array_keys($aggregated_revisions);
227
		}
228
229
		$last_revision = end($revisions);
230
231
		$project_path = $revision_log->getProjectPath();
232
233
		$bugs_per_row = $with_details ? 1 : 3;
234
235
		$revisions_data = $revision_log->getRevisionsData('summary', $revisions);
236
		$revisions_paths = $revision_log->getRevisionsData('paths', $revisions);
237
		$revisions_bugs = $revision_log->getRevisionsData('bugs', $revisions);
238
		$revisions_refs = $revision_log->getRevisionsData('refs', $revisions);
239
240
		if ( $with_merge_status ) {
241
			$revisions_merged_via = $revision_log->getRevisionsData('merges', $revisions);
242
			$revisions_merged_via_refs = $revision_log->getRevisionsData(
243
				'refs',
244
				call_user_func_array('array_merge', $revisions_merged_via)
245
			);
246
		}
247
248
		$revision_url_mask = $revision_log->getRevisionURLBuilder()->getMask();
249
250
		// Use mask only, when it contains an URL.
251
		if ( strpos($revision_url_mask, '://') === false ) {
252
			$revision_url_mask = '';
253
		}
254
255
		$first_revision = reset($revisions);
256
257
		foreach ( $revisions as $revision ) {
258
			$revision_data = $revisions_data[$revision];
259
260
			$new_bugs = $revisions_bugs[$revision];
261
262
			if ( isset($prev_bugs) && $new_bugs !== $prev_bugs ) {
263
				$last_bug_color = $last_bug_color === 'yellow' ? 'magenta' : 'yellow';
264
			}
265
266
			$row = array(
267
				$this->_aggregateByBug ? $aggregated_revisions[$revision] . ' cmts' : $revision,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $aggregated_revisions does not seem to be defined for all execution paths leading up to this point.
Loading history...
268
				$revision_data['author'],
269
				$this->_dateHelper->getAgoTime($revision_data['date']),
270
				$this->_outputHelper->formatArray($new_bugs, $bugs_per_row, $last_bug_color),
271
				$this->_generateLogMessageColumn($with_full_message || $with_details, $revision_data),
272
			);
273
274
			$revision_paths = $revisions_paths[$revision];
275
276
			// Add "Summary" column.
277
			if ( $with_summary ) {
278
				$row[] = $this->_generateSummaryColumn($revision_paths);
279
			}
280
281
			// Add "Refs" column.
282
			if ( $with_refs ) {
283
				$row[] = $this->_outputHelper->formatArray(
284
					$revisions_refs[$revision],
285
					1
286
				);
287
			}
288
289
			// Add "M.O." column.
290
			if ( $with_merge_oracle ) {
291
				$merge_conflict_prediction = $this->_getMergeConflictPrediction($revision_paths);
292
				$row[] = $merge_conflict_prediction ? '<error>' . count($merge_conflict_prediction) . '</error>' : '';
293
			}
294
			else {
295
				$merge_conflict_prediction = array();
296
			}
297
298
			// Add "Merged Via" column.
299
			if ( $with_merge_status ) {
300
				$row[] = $this->_generateMergedViaColumn($revisions_merged_via[$revision], $revisions_merged_via_refs);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $revisions_merged_via_refs does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $revisions_merged_via does not seem to be defined for all execution paths leading up to this point.
Loading history...
301
			}
302
303
			if ( $revision === $this->_currentRevision ) {
304
				foreach ( $row as $index => $cell ) {
305
					$row[$index] = $this->applyStyle($cell, 'fg=white;options=bold');
306
				}
307
			}
308
309
			if ( $with_full_message && $revision !== $first_revision ) {
310
				$table->addRow(new TableSeparator());
311
			}
312
313
			$table->addRow($row);
314
315
			if ( $with_details ) {
316
				$details = $this->_generateDetailsRowContent(
317
					$revision,
318
					$revisions_refs,
319
					$revision_paths,
320
					$merge_conflict_prediction,
321
					$project_path,
322
					$revision_url_mask
323
				);
324
325
				$table->addRow(new TableSeparator());
326
				$table->addRow(array(
327
					new TableCell($details, array('colspan' => count($headers))),
328
				));
329
330
				if ( $revision != $last_revision ) {
331
					$table->addRow(new TableSeparator());
332
				}
333
			}
334
335
			$prev_bugs = $new_bugs;
336
		}
337
338
		$table->render();
339
340
		$this->_resetState();
341
	}
342
343
	/**
344
	 * Aggregates revisions by bugs.
345
	 *
346
	 * @param array       $revisions    Revisions.
347
	 * @param RevisionLog $revision_log Revision Log.
348
	 *
349
	 * @return array
350
	 */
351
	protected function aggregateRevisionsByBug(array $revisions, RevisionLog $revision_log)
352
	{
353
		$bugs_revisions = array(
354
			'unknown' => array(),
355
		);
356
357
		$revisions_bugs = $revision_log->getRevisionsData('bugs', $revisions);
358
359
		foreach ( \array_reverse($revisions) as $revision ) {
360
			$revision_bugs = $revisions_bugs[$revision];
361
362
			if ( !$revision_bugs ) {
363
				$bugs_revisions['unknown'][] = $revision;
364
				continue;
365
			}
366
367
			foreach ( $revision_bugs as $revision_bug ) {
368
				if ( !isset($bugs_revisions[$revision_bug]) ) {
369
					$bugs_revisions[$revision_bug] = array();
370
				}
371
372
				$bugs_revisions[$revision_bug][] = $revision;
373
			}
374
		}
375
376
		if ( !$bugs_revisions['unknown'] ) {
377
			unset($bugs_revisions['unknown']);
378
		}
379
380
		$bugs_revisions = \array_reverse($bugs_revisions, true);
381
382
		$ret = array();
383
384
		foreach ( $bugs_revisions as $bug => $bug_revisions ) {
385
			$ret[reset($bug_revisions)] = count($bug_revisions);
386
		}
387
388
		return $ret;
389
	}
390
391
	/**
392
	 * Applies a style to the text.
393
	 *
394
	 * @param string $text  Text.
395
	 * @param string $style Style.
396
	 *
397
	 * @return string
398
	 */
399
	protected function applyStyle($text, $style)
400
	{
401
		if ( strpos($text, PHP_EOL) === false ) {
402
			return '<' . $style . '>' . $text . '</>';
403
		}
404
405
		$lines = explode(PHP_EOL, $text);
406
407
		return '<' . $style . '>' . implode('</>' . PHP_EOL . '<' . $style . '>', $lines) . '</>';
408
	}
409
410
	/**
411
	 * Returns log message.
412
	 *
413
	 * @param boolean $with_full_message Show commit message without truncation.
414
	 * @param array   $revision_data     Revision data.
415
	 *
416
	 * @return string
417
	 */
418
	private function _generateLogMessageColumn($with_full_message, array $revision_data)
419
	{
420
		$commit_message = trim($revision_data['msg']);
421
422
		if ( $with_full_message ) {
423
			// When details requested don't transform commit message except for word wrapping.
424
			// FIXME: Not UTF-8 safe solution.
425
			$log_message = wordwrap($commit_message, $this->_logMessageLimit);
426
427
			return $log_message;
428
		}
429
		else {
430
			// When details not requested only operate on first line of commit message.
431
			list($log_message,) = explode(PHP_EOL, $commit_message);
432
			$log_message = preg_replace('/(^|\s+)\[fixes:.*?\]/s', "$1\xE2\x9C\x94", $log_message);
433
434
			if ( strpos($commit_message, PHP_EOL) !== false
435
				|| mb_strlen($log_message) > $this->_logMessageLimit
436
			) {
437
				$log_message = mb_substr($log_message, 0, $this->_logMessageLimit - 3) . '...';
438
439
				return $log_message;
440
			}
441
442
			return $log_message;
443
		}
444
	}
445
446
	/**
447
	 * Generates change summary for a revision.
448
	 *
449
	 * @param array $revision_paths Revision paths.
450
	 *
451
	 * @return string
452
	 */
453
	private function _generateSummaryColumn(array $revision_paths)
454
	{
455
		$summary = array('added' => 0, 'changed' => 0, 'removed' => 0);
456
457
		foreach ( $revision_paths as $path_data ) {
458
			$path_action = $path_data['action'];
459
460
			if ( $path_action === 'A' ) {
461
				$summary['added']++;
462
			}
463
			elseif ( $path_action === 'D' ) {
464
				$summary['removed']++;
465
			}
466
			else {
467
				$summary['changed']++;
468
			}
469
		}
470
471
		if ( $summary['added'] ) {
472
			$summary['added'] = '<fg=green>+' . $summary['added'] . '</>';
473
		}
474
475
		if ( $summary['removed'] ) {
476
			$summary['removed'] = '<fg=red>-' . $summary['removed'] . '</>';
477
		}
478
479
		return implode(' ', array_filter($summary));
480
	}
481
482
	/**
483
	 * Returns merge conflict path predictions.
484
	 *
485
	 * @param array $revision_paths Revision paths.
486
	 *
487
	 * @return array
488
	 */
489
	private function _getMergeConflictPrediction(array $revision_paths)
490
	{
491
		if ( !$this->_mergeConflictRegExps ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_mergeConflictRegExps of type array 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...
492
			return array();
493
		}
494
495
		$conflict_paths = array();
496
497
		foreach ( $revision_paths as $revision_path ) {
498
			foreach ( $this->_mergeConflictRegExps as $merge_conflict_regexp ) {
499
				if ( preg_match($merge_conflict_regexp, $revision_path['path']) ) {
500
					$conflict_paths[] = $revision_path['path'];
501
				}
502
			}
503
		}
504
505
		return $conflict_paths;
506
	}
507
508
	/**
509
	 * Generates content for "Merged Via" cell content.
510
	 *
511
	 * @param array $merged_via                Merged Via.
512
	 * @param array $revisions_merged_via_refs Merged Via Refs.
513
	 *
514
	 * @return string
515
	 */
516
	private function _generateMergedViaColumn(array $merged_via, array $revisions_merged_via_refs)
517
	{
518
		if ( !$merged_via ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $merged_via of type array 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...
519
			return '';
520
		}
521
522
		$merged_via_enhanced = array();
523
524
		foreach ( $merged_via as $merged_via_revision ) {
525
			$merged_via_revision_refs = $revisions_merged_via_refs[$merged_via_revision];
526
527
			if ( $merged_via_revision_refs ) {
528
				$merged_via_enhanced[] = $merged_via_revision . ' (' . implode(',', $merged_via_revision_refs) . ')';
529
			}
530
			else {
531
				$merged_via_enhanced[] = $merged_via_revision;
532
			}
533
		}
534
535
		return $this->_outputHelper->formatArray($merged_via_enhanced, 1);
536
	}
537
538
	/**
539
	 * Generates details row content.
540
	 *
541
	 * @param integer $revision                  Revision.
542
	 * @param array   $revisions_refs            Refs.
543
	 * @param array   $revision_paths            Revision paths.
544
	 * @param array   $merge_conflict_prediction Merge conflict prediction.
545
	 * @param string  $project_path              Project path.
546
	 * @param string  $revision_url_mask         Revision URL mask.
547
	 *
548
	 * @return string
549
	 */
550
	private function _generateDetailsRowContent(
551
		$revision,
552
		array $revisions_refs,
553
		array $revision_paths,
554
		array $merge_conflict_prediction,
555
		$project_path,
556
		$revision_url_mask
557
	) {
558
		$details = '';
559
560
		if ( $revision_url_mask ) {
561
			$details .= '<fg=white;options=bold>Revision URL:</>' . PHP_EOL;
562
			$details .= str_replace('{revision}', $revision, $revision_url_mask) . PHP_EOL . PHP_EOL;
563
		}
564
565
		$details .= '<fg=white;options=bold>Changed Paths:</>';
566
		$path_cut_off_regexp = $this->getPathCutOffRegExp($project_path, $revisions_refs[$revision]);
567
568
		foreach ( $revision_paths as $path_data ) {
569
			$path_action = $path_data['action'];
570
			$relative_path = $this->_getRelativeLogPath($path_data, 'path', $path_cut_off_regexp);
571
572
			$details .= PHP_EOL . ' * ';
573
574
			if ( $path_action === 'A' ) {
575
				$color_format = 'fg=green';
576
			}
577
			elseif ( $path_action === 'D' ) {
578
				$color_format = 'fg=red';
579
			}
580
			else {
581
				$color_format = in_array($path_data['path'], $merge_conflict_prediction) ? 'error' : '';
582
			}
583
584
			$to_colorize = array($path_action . '    ' . $relative_path);
585
586
			if ( isset($path_data['copyfrom-path']) ) {
587
				// TODO: When copy happened from different ref/project, then relative path = absolute path.
588
				$copy_from_rev = $path_data['copyfrom-rev'];
589
				$copy_from_path = $this->_getRelativeLogPath($path_data, 'copyfrom-path', $path_cut_off_regexp);
590
				$to_colorize[] = '        (from ' . $copy_from_path . ':' . $copy_from_rev . ')';
591
			}
592
593
			if ( $color_format ) {
594
				$details .= '<' . $color_format . '>';
595
				$details .= implode('</>' . PHP_EOL . '<' . $color_format . '>', $to_colorize);
596
				$details .= '</>';
597
			}
598
			else {
599
				$details .= implode(PHP_EOL, $to_colorize);
600
			}
601
		}
602
603
		return $details;
604
	}
605
606
	/**
607
	 * Returns path cut off regexp.
608
	 *
609
	 * @param string $project_path Project path.
610
	 * @param array  $refs         Refs.
611
	 *
612
	 * @return string
613
	 */
614
	protected function getPathCutOffRegExp($project_path, array $refs)
0 ignored issues
show
Unused Code introduced by
The parameter $refs is not used and could be removed. ( Ignorable by Annotation )

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

614
	protected function getPathCutOffRegExp($project_path, /** @scrutinizer ignore-unused */ array $refs)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
615
	{
616
		$ret = array();
617
618
		// Remove ref from path only for single-ref revision.
619
		/*if ( count($refs) === 1 ) {
620
			$ret[] = $project_path . reset($refs) . '/';
621
		}*/
622
623
		// Always remove project path.
624
		$ret[] = $project_path;
625
626
		return '#^(' . implode('|', array_map('preg_quote', $ret)) . ')#';
627
	}
628
629
	/**
630
	 * Returns relative path to "svn log" returned path.
631
	 *
632
	 * @param array  $path_data           Path data.
633
	 * @param string $path_key            Path key.
634
	 * @param string $path_cut_off_regexp Path cut off regexp.
635
	 *
636
	 * @return string
637
	 */
638
	private function _getRelativeLogPath(array $path_data, $path_key, $path_cut_off_regexp)
639
	{
640
		$ret = preg_replace($path_cut_off_regexp, '', $path_data[$path_key], 1);
641
642
		if ( $ret === '' ) {
643
			$ret = '.';
644
		}
645
646
		return $ret;
647
	}
648
649
}
650