1+ <?php declare (strict_types=1 );
2+
3+ namespace TeddyBear06 \EdgeDbPhp ;
4+
5+ use TeddyBear06 \EdgeDbPhp \EdgeDbQuery ;
6+ use GuzzleHttp \Client ;
7+
8+ /**
9+ * An unofficial naive EdgeDB PHP client using EdgeDB HTTP protocol.
10+ *
11+ * See https://www.edgedb.com/docs/clients/90_edgeql/index for more informations about
12+ * how to activate it on your EdgeDB instance.
13+ */
14+ class EdgeDbClient {
15+
16+ /**
17+ * EdgeDB hostname (or IP).
18+ *
19+ * @var string
20+ */
21+ private string $ hostname ;
22+
23+ /**
24+ * EdgeDB port.
25+ *
26+ * @var integer
27+ */
28+ private int $ port ;
29+
30+ /**
31+ * EdgeDB database name.
32+ *
33+ * @var string
34+ */
35+ private string $ database ;
36+
37+ /**
38+ * Indicates whether or not the client should display debug infos.
39+ *
40+ * @var bool
41+ */
42+ private bool $ debug ;
43+
44+ /**
45+ * Guzzle client.
46+ *
47+ * @var Client
48+ */
49+ private $ client ;
50+
51+ /**
52+ * Creates an EdgeDB PHP client instance.
53+ *
54+ * @var string $hostname The EdgeDB server hostname (or IP).
55+ * @var int $port The EdgeDB server port.
56+ * @var string $database The EdgeDB database name.
57+ * @var bool $debug Indicates whether or not the client should display debug infos.
58+ */
59+ public function __construct (string $ hostname = '127.0.0.1 ' , int $ port = 10700 , string $ database = 'edgedb ' , bool $ debug = false )
60+ {
61+ $ this ->hostname = $ hostname ;
62+ $ this ->port = $ port ;
63+ $ this ->database = $ database ;
64+ $ this ->debug = $ debug ;
65+ $ this ->client = new Client ([
66+ 'base_uri ' => sprintf ('http://%s:%d/db/%s/edgeql ' , $ this ->hostname , $ this ->port , $ this ->database )
67+ ]);
68+ }
69+
70+ /**
71+ * Send an HTTP request against an EdgeDB server instance.
72+ *
73+ * @var EdgeDbQuery $query The EdgeDB query.
74+ * @return array
75+ */
76+ public function send (EdgeDbQuery $ query ): array
77+ {
78+ $ options = [
79+ 'json ' => $ query ->getQuery (),
80+ 'debug ' => $ this ->debug
81+ ];
82+
83+ $ response = $ this ->client ->request ('POST ' , '' , $ options );
84+
85+ $ body = $ response ->getBody ();
86+
87+ $ json = json_decode ($ body ->__toString (), true );
88+
89+ if ($ this ->debug ) {
90+ $ json ['debug ' ] = [
91+ 'jsonQuery ' => $ query ->getQuery ()
92+ ];
93+ }
94+
95+ return $ json ;
96+ }
97+
98+ }
0 commit comments