Passed
Push — main ( 76b212...64ce86 )
by Jean-Christophe
02:16
created

ReactJS::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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