Passed
Push — main ( ed2574...e49322 )
by Jean-Christophe
02:38
created

ReactJS::renderComponent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 1
eloc 4
c 2
b 0
f 2
nc 1
nop 2
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
namespace PHPMV\react;
3
4
use PHPMV\core\TemplateParser;
5
use PHPMV\utils\JSX;
6
use PHPMV\js\JavascriptUtils;
7
use PHPMV\core\ReactLibrary;
8
9
/**
10
 * The ReactJS service for PHP.
11
 * PHPMV\react$ReactJS
12
 * This class is part of php-reactjs
13
 *
14
 * @author jc
15
 * @version 1.0.0
16
 *
17
 */
18
class ReactJS {
19
20
	/**
21
	 *
22
	 * @var array
23
	 */
24
	private $operations;
25
26
	public $components;
27
28
	/**
29
	 *
30
	 * @var TemplateParser
31
	 */
32
	private $renderTemplate;
33
34
	/**
35
	 * Initialize templates.
36
	 */
37
	public function __construct() {
38
		$this->operations = [];
39
		$this->components = [];
40
		$this->renderTemplate = new TemplateParser();
41
		$this->renderTemplate->loadTemplatefile(ReactLibrary::getTemplateFolder() . '/renderComponent');
42
		ReactComponent::init();
43
	}
44
45
	/**
46
	 * Insert a react component in the DOM.
47
	 *
48
	 * @param string $jsxHtml
49
	 * @param string $selector
50
	 * @return string
51
	 */
52
	public function renderComponent(string $jsxHtml, string $selector): string {
53
		return ($this->operations[] = function () use ($selector, $jsxHtml) {
54
			return $this->renderTemplate->parse([
55
				'selector' => $selector,
56
				'component' => JSX::toJs($jsxHtml, $this)
57
			]);
58
		})();
59
	}
60
61
	/**
62
	 * Create and return a new ReactComponent.
63
	 *
64
	 * @param string $name
65
	 * @param bool $compile
66
	 * @return ReactComponent
67
	 */
68
	public function createComponent(string $name, $compile = true): ReactComponent {
69
		$compo = new ReactComponent($name, $this);
70
		$this->components[\strtolower($name)] = $name;
71
		if ($compile) {
72
			$this->operations[] = function () use ($compo) {
73
				return $compo->parse();
74
			};
75
		}
76
		return $compo;
77
	}
78
79
	/**
80
	 * Generate the javascript code.
81
	 *
82
	 * @return string
83
	 */
84
	public function compile(): string {
85
		$script = '';
86
		foreach ($this->operations as $op) {
87
			$script .= $op();
88
		}
89
		return JavascriptUtils::wrapScript($script);
90
	}
91
92
	public function __toString() {
93
		return $this->compile();
94
	}
95
}
96
97