Commit | Line | Data |
---|---|---|
54675f57 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
4 | | Copyright CiviCRM LLC. All rights reserved. | | |
5 | | | | |
6 | | This work is published under the GNU AGPLv3 license with some | | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
9 | +--------------------------------------------------------------------+ | |
10 | */ | |
11 | ||
12 | namespace Civi\Pipe; | |
13 | ||
25804d7a | 14 | class PipeSession { |
54675f57 TO |
15 | |
16 | use LineSessionTrait; | |
17 | ||
18 | protected const METHOD_REGEX = ';^[a-z][a-zA-Z0-9_]*$;'; | |
19 | ||
20 | /** | |
21 | * Open-ended object. Any public method will be available during this session. | |
22 | * | |
23 | * @var object | |
24 | */ | |
25 | protected $methods; | |
26 | ||
5e13f388 TO |
27 | /** |
28 | * @var bool|null | |
29 | */ | |
30 | protected $trusted; | |
31 | ||
54675f57 TO |
32 | /** |
33 | * @inheritDoc | |
34 | */ | |
35 | protected function onConnect(): ?string { | |
36 | \CRM_Core_Session::useFakeSession(); | |
37 | $this->methods = new PublicMethods(); | |
38 | return json_encode(["Civi::pipe" => ['jsonrpc20']]); | |
39 | } | |
40 | ||
41 | /** | |
42 | * @inheritDoc | |
43 | */ | |
44 | protected function onRequest(string $requestLine): ?string { | |
158d477b TO |
45 | return JsonRpc::run($requestLine, function($method, $params) { |
46 | $method = str_replace('.', '_', $method); | |
47 | if (!preg_match(self::METHOD_REGEX, $method)) { | |
48 | throw new \InvalidArgumentException('Method not found', -32601); | |
54675f57 TO |
49 | } |
50 | ||
51 | if (!is_callable([$this->methods, $method])) { | |
52 | throw new \InvalidArgumentException('Method not found', -32601); | |
53 | } | |
54 | ||
158d477b TO |
55 | return call_user_func([$this->methods, $method], $this, $params); |
56 | }); | |
54675f57 TO |
57 | } |
58 | ||
59 | /** | |
60 | * @inheritDoc | |
61 | */ | |
62 | protected function onException(string $requestLine, \Throwable $t): ?string { | |
158d477b TO |
63 | $error = JsonRpc::createResponseError([], $t); |
64 | return \json_encode($error); | |
54675f57 TO |
65 | } |
66 | ||
5e13f388 TO |
67 | /** |
68 | * @param bool $trusted | |
69 | * @return PipeSession | |
70 | */ | |
71 | public function setTrusted(bool $trusted): PipeSession { | |
72 | if ($this->trusted !== NULL && $this->trusted !== $trusted) { | |
73 | throw new \CRM_Core_Exception('Cannot modify PipeSession::$trusted after initialization'); | |
74 | } | |
75 | $this->trusted = $trusted; | |
76 | return $this; | |
77 | } | |
78 | ||
79 | /** | |
80 | * @return bool | |
81 | */ | |
82 | public function isTrusted(): bool { | |
83 | // If this gets called when the value is NULL, then you are doing it wrong. | |
84 | return $this->trusted; | |
85 | } | |
86 | ||
54675f57 | 87 | } |