Skip to content

Commit 327a10e

Browse files
committed
Adds options and table printing to php version
1 parent 14f877a commit 327a10e

File tree

1 file changed

+49
-9
lines changed

1 file changed

+49
-9
lines changed

composer-lock-diff.php

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
#!/usr/bin/env php
22
<?php
33

4-
print "production packages\n===================\n";
5-
print_pkgs(diff('packages'));
4+
$prod = diff('packages');
5+
$dev = diff('packages-dev');
66

7-
print "\ndev packages\n============\n";
8-
print_pkgs(diff('packages-dev'));
7+
if (hasOpt('json')) {
8+
$opts = (hasOpt('pretty')) ? JSON_PRETTY_PRINT : 0;
9+
print json_encode(array('changes' => $prod, 'changes-dev' => $dev), $opts);
10+
return;
11+
}
12+
13+
print tableize('Production Changes', $prod);
14+
print tableize('Dev Changes', $dev);
915

1016
function diff($key) {
1117

@@ -37,12 +43,46 @@ function diff($key) {
3743
return $pkgs;
3844
}
3945

40-
function print_pkgs($pkgs) {
46+
function hasOpt($opt) {
47+
global $argv;
48+
$prefix = strlen($opt) === 1 ? '-' : '--';
49+
return in_array($prefix.$opt, $argv);
50+
}
51+
52+
function tableize($header, $data) {
53+
$widths = array(maxLength(array_merge(array($header), array_keys($data))));
54+
55+
for($i = 0; $i < count(reset($data)); $i++) {
56+
$widths[] = maxLength(array_map(function($k) use ($data, $i) { return $data[$k][$i]; }, array_keys($data)));
57+
}
58+
59+
$total_width = array_sum($widths) + (count($widths) * 3) + 1;
60+
61+
$lines[] = '+' . str_repeat('-', $total_width - 2) . '+';
62+
$lines[] = tabelizeLine(array($header, 'From', 'To'), $widths);
63+
$lines[] = '+' . str_repeat('-', $total_width - 2) . '+';
64+
65+
foreach($data as $key => $v) {
66+
$lines[] = tabelizeLine(array_merge(array($key), $v), $widths);
67+
}
68+
69+
$lines[] = '+' . str_repeat('-', $total_width - 2) . '+';
70+
71+
return implode(PHP_EOL, $lines) . PHP_EOL;
72+
}
73+
74+
function maxLength(array $array) {
75+
return max(array_map('strlen', $array));
76+
}
4177

42-
$pkg_width = max(array_map('strlen', array_keys($pkgs))) + 1;
43-
$before_width = max(array_map('strlen', array_map(function($v) { return $v[0]; }, $pkgs)));
44-
foreach($pkgs as $name => $v) {
45-
printf("%-{$pkg_width}s %-{$before_width}s => %s\n", $name, $v[0], $v[1]);
78+
function tabelizeLine($data, $widths) {
79+
$fields = array();
80+
$count = max(array(count($data), count($widths)));
81+
for($i = 0; $i < $count; $i++) {
82+
$value = ($i >= count($data)) ? '' : $data[$i];
83+
$width = ($i >= count($widths)) ? strlen($value) : $widths[$i];
84+
$fields[] = sprintf("%-{$width}s", $value);
4685
}
86+
return '| ' . implode(' | ', $fields) . ' |';
4787
}
4888

0 commit comments

Comments
 (0)