CS fixes
[phorkie.git] / src / phorkie / Renderer / ReStructuredText.php
1 <?php
2 namespace phorkie;
3
4 /**
5  * Requires cli program "rst2html" (python docutils) to be installed
6  */
7 class Renderer_ReStructuredText
8 {
9     /**
10      * Converts the rST to HTML
11      *
12      * @param File $file File to render
13      *
14      * @return string HTML
15      */
16     public function toHtml(File $file)
17     {
18         $descriptorspec = array(
19             0 => array('pipe', 'r'),//stdin
20             1 => array('pipe', 'w'),//stdout
21             2 => array('pipe', 'w') //stderr
22         );
23         $process = proc_open('rst2html', $descriptorspec, $pipes);
24         if (!is_resource($process)) {
25             return '<div class="alert alert-error">'
26                 . 'Cannot open process to execute rst2html'
27                 . '</div>';
28         }
29
30         fwrite($pipes[0], $file->getContent());
31         fclose($pipes[0]);
32
33         $html = stream_get_contents($pipes[1]);
34         fclose($pipes[1]);
35
36         $errors = stream_get_contents($pipes[2]);
37         fclose($pipes[2]);
38
39         $retval = proc_close($process);
40
41         //cheap extraction of the rst html body
42         $html = substr($html, strpos($html, '<body>') + 6);
43         $html = substr($html, 0, strpos($html, '</body>'));
44
45         if ($retval != 0) {
46             $html = '<div class="alert">'
47                 . 'rst2html encountered some error; return value '
48                 . $retval . '<br/>'
49                 . 'Error message: ' . $errors
50                 . '</div>'
51                 . $html;
52         }
53
54         return $html;
55     }
56 }
57
58 ?>