Passed
Push — main ( faf76d...59f012 )
by Jean-Christophe
02:21
created

ReactJS::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
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 3
	public function __construct() {
38 3
		$this->operations = [];
39 3
		$this->components = [];
40 3
		$this->renderTemplate = new TemplateParser();
41 3
		$this->renderTemplate->loadTemplatefile(ReactLibrary::getTemplateFolder() . '/renderComponent');
42 3
		ReactComponent::init();
43 3
	}
44
45
	/**
46
	 * Insert a react component in the DOM.
47
	 *
48
	 * @param string $jsxHtml
49
	 * @param string $selector
50
	 * @return string
51
	 */
52 3
	public function renderComponent(string $jsxHtml, string $selector): string {
53 3
		return ($this->operations[] = function () use ($selector, $jsxHtml) {
54 3
			return $this->renderTemplate->parse([
55 3
				'selector' => $selector,
56 3
				'component' => JSX::toJs($jsxHtml, $this)
57
			]);
58 3
		})();
59
	}
60
61
	/**
62
	 * Create and return a new ReactComponent.
63
	 *
64
	 * @param string $name
65
	 * @param bool $compile
66
	 * @return ReactComponent
67
	 */
68 3
	public function createComponent(string $name, $compile = true): ReactComponent {
69 3
		$compo = new ReactComponent($name, $this);
70 3
		$this->components[\strtolower($name)] = $name;
71 3
		if ($compile) {
72 3
			$this->operations[] = function () use ($compo) {
73 3
				return $compo->parse();
74
			};
75
		}
76 3
		return $compo;
77
	}
78
79
	/**
80
	 * Generate the javascript code.
81
	 *
82
	 * @return string
83
	 */
84 3
	public function compile(): string {
85 3
		$script = '';
86 3
		foreach ($this->operations as $op) {
87 3
			$script .= $op();
88
		}
89 3
		return JavascriptUtils::wrapScript($script);
90
	}
91
92 2
	public function __toString() {
93 2
		return $this->compile();
94
	}
95
}
96
97