Completed
Push — master ( 14218a...10a4b7 )
by Jeroen De
03:39
created

GitHubParserHook::getRenderedContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
3
namespace GitHub;
4
5
use FileFetcher\FileFetcher;
6
use Michelf\Markdown;
7
use ParamProcessor\ProcessingResult;
8
use Parser;
9
use ParserHooks\HookHandler;
10
11
/**
12
 * @licence GNU GPL v2+
13
 * @author Jeroen De Dauw < [email protected] >
14
 */
15
class GitHubParserHook implements HookHandler {
16
17
	private $fileFetcher;
18
	private $gitHubUrl;
19
20
	private $fileName;
21
	private $repoName;
22
	private $branchName;
23
24
	/**
25
	 * @param FileFetcher $fileFetcher
26
	 * @param string $gitHubUrl
27
	 */
28
	public function __construct( FileFetcher $fileFetcher, $gitHubUrl ) {
29
		$this->fileFetcher = $fileFetcher;
30
		$this->gitHubUrl = $gitHubUrl;
31
	}
32
33
	public function handle( Parser $parser, ProcessingResult $result ) {
34
		$this->setFields( $result );
35
36
		return $this->getRenderedContent();
37
	}
38
39
	private function setFields( ProcessingResult $result ) {
40
		$params = $result->getParameters();
41
42
		$this->fileName = $params['file']->getValue();
43
		$this->repoName = $params['repo']->getValue();
44
		$this->branchName = $params['branch']->getValue();
45
	}
46
47
	private function getRenderedContent() {
48
		$content = $this->getFileContent();
49
50
		if ( $this->isMarkdownFile() ) {
51
			$content = $this->renderAsMarkdown( $content );
52
		}
53
54
		return $content;
55
	}
56
57
	private function getFileContent() {
58
		return $this->fileFetcher->fetchFile( $this->getFileUrl() );
59
	}
60
61
	private function getFileUrl() {
62
		return sprintf(
63
			'%s/%s/%s/%s',
64
			$this->gitHubUrl,
65
			$this->repoName,
66
			$this->branchName,
67
			$this->fileName
68
		);
69
	}
70
71
	private function isMarkdownFile() {
72
		return $this->fileHasExtension( 'md' ) || $this->fileHasExtension( 'markdown' );
73
	}
74
75
	private function fileHasExtension( $extension ) {
76
		$fullExtension = '.' . $extension;
77
		return substr( $this->fileName, -strlen( $fullExtension ) ) === $fullExtension;
78
	}
79
80
	private function renderAsMarkdown( $content ) {
81
		return Markdown::defaultTransform( $content );
82
	}
83
84
}
85