Created
March 10, 2015 15:23
-
-
Save hypermkt/fd79c01fa3f1e7fdef91 to your computer and use it in GitHub Desktop.
Sequel Pro: copyAsMarkdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/php | |
<?php | |
$stdIn = fopen("php://stdin", "r"); | |
$result = []; | |
while($row = fgetcsv($stdIn, 0)) { | |
array_push($result, $row); | |
} | |
$c = new CsvToMarkdownConverter(); | |
$cmd = 'echo ' . escapeshellarg($c->convert($result)) .' | __CF_USER_TEXT_ENCODING='.posix_getuid().':0x8000100:0x8000100 pbcopy'; | |
shell_exec($cmd); | |
class CsvToMarkdownConverter | |
{ | |
protected $_output; | |
protected $_columnCount; | |
public function convert(array $rows) | |
{ | |
$this->_columnCount = $this->_calculateColumnCount($rows); | |
$columns = array_shift($rows); | |
$result = []; | |
$result[] =$this->_createHeaderRows($columns); | |
$result[] = $this->_createDataRows($rows); | |
return implode("\n", $result); | |
} | |
protected function _createHeaderRows(array $columns) | |
{ | |
$result = []; | |
$str = ''; | |
foreach ($columns as $column) { | |
if (!empty($str)) { | |
$str .= "|"; | |
} | |
$str .= $column; | |
} | |
$result[] = $str; | |
$str = ''; | |
for($i=0; $i<count($columns); $i++) { | |
if (!empty($str)) { | |
$str .= "|"; | |
} | |
$str .= "---"; | |
} | |
$result[] = $str; | |
return implode("\n", $result); | |
} | |
protected function _calculateColumnCount(array $rows) | |
{ | |
$count = 0; | |
foreach ($rows as $row) { | |
$c = count($row); | |
if ($c > $count) { | |
$count = $c; | |
} | |
} | |
return $count; | |
} | |
protected function _createDataRows(array $rows) | |
{ | |
$result = []; | |
foreach ($rows as $row) { | |
$str = ''; | |
foreach ($row as $val) { | |
if (!empty($str)) { | |
$str .= "|"; | |
} | |
$str .= $val; | |
} | |
$result[] = $str; | |
} | |
return implode("\n", $result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment