1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jaxon\Script\Call; |
4
|
|
|
|
5
|
|
|
use JsonSerializable; |
6
|
|
|
use Stringable; |
7
|
|
|
|
8
|
|
|
use function is_a; |
9
|
|
|
use function trim; |
10
|
|
|
|
11
|
|
|
class Selector implements JsonSerializable, Stringable |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $sScript; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var array |
20
|
|
|
*/ |
21
|
|
|
private $aCall; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* The constructor. |
25
|
|
|
* |
26
|
|
|
* @param string $sMode The selector mode: 'jq' or 'js' |
27
|
|
|
* @param string $sPath The selector path |
28
|
|
|
* @param mixed $xContext A context associated to the selector |
29
|
|
|
*/ |
30
|
|
|
public function __construct(string $sMode, string $sPath, $xContext = null) |
31
|
|
|
{ |
32
|
|
|
$sName = trim($sPath) ?: 'this'; |
33
|
|
|
$this->aCall = ['_type' => 'select', '_name' => $sName, 'mode' => $sMode]; |
34
|
|
|
if(($sPath) && ($xContext)) |
35
|
|
|
{ |
36
|
|
|
$this->aCall['context'] = is_a($xContext, JsonSerializable::class) ? |
37
|
|
|
$xContext->jsonSerialize() : $xContext; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->sScript = $this->getPathAsStr($sName, $sMode, $xContext); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Get the selector js. |
45
|
|
|
* |
46
|
|
|
* @param string $sPath The jQuery selector path |
47
|
|
|
* @param string $sMode The selector mode: 'jq' or 'js' |
48
|
|
|
* @param mixed $xContext A context associated to the selector |
49
|
|
|
* |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
|
|
private function getPathAsStr(string $sPath, string $sMode, $xContext) |
53
|
|
|
{ |
54
|
|
|
if(!$xContext) |
55
|
|
|
{ |
56
|
|
|
return $sMode === 'jq' ? "jaxon.jq('$sPath')" : $sPath; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$sContext = is_a($xContext, self::class) ? |
60
|
|
|
$xContext->__toString() : "jaxon.jq('" . trim("{$xContext}") . "')"; |
61
|
|
|
return "jaxon.jq('{$sPath}', $sContext)"; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Convert this call to array, when converting the response into json. |
66
|
|
|
* |
67
|
|
|
* @return array |
68
|
|
|
*/ |
69
|
|
|
public function jsonSerialize(): array |
70
|
|
|
{ |
71
|
|
|
return $this->aCall; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Returns a string representation of this call |
76
|
|
|
* |
77
|
|
|
* @return string |
78
|
|
|
*/ |
79
|
|
|
public function __toString(): string |
80
|
|
|
{ |
81
|
|
|
return $this->sScript; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|