throw exception when search throws exception
[phorkie.git] / src / phorkie / Search / Elasticsearch.php
1 <?php
2 namespace phorkie;
3
4 class Search_Elasticsearch
5 {
6     public function __construct()
7     {
8         $this->searchInstance = $GLOBALS['phorkie']['cfg']['elasticsearch'];
9     }
10
11     /**
12      * Search for a given term and return repositories that contain it
13      * in their description, file names or file content
14      *
15      * @param string  $term    Search term
16      * @param integer $page    Page of search results, starting with 0
17      * @param integer $perPage Number of results per page
18      *
19      * @return Search_Result Search result object
20      */
21     public function search($term, $page = 0, $perPage = 10)
22     {
23         $r = new \HTTP_Request2(
24             $this->searchInstance . 'repo/_search',
25             \HTTP_Request2::METHOD_GET
26         );
27         $r->setBody(
28             json_encode(
29                 (object)array(
30                     'from' => $page * $perPage,
31                     'size' => $perPage,
32                     'query' => (object)array(
33                         'bool' => (object)array(
34                             'should' => array(
35                                 (object)array(
36                                     'query_string' => (object)array(
37                                         'query' => $term
38                                     ),
39                                 ),
40                                 (object)array(
41                                     'has_child' => (object)array(
42                                         'type'         => 'file',
43                                         'query' => (object)array(
44                                             'query_string' => (object)array(
45                                                 'query' => $term
46                                             )
47                                         )
48                                     )
49                                 )
50                             )
51                         )
52                     )
53                 )
54             )
55         );
56         $httpRes = $r->send();
57         $jRes = json_decode($httpRes->getBody());
58         if (isset($jRes->error)) {
59             throw new Exception(
60                 'Search exception: ' . $jRes->error, $jRes->status
61             );
62         }
63
64         $sres = new Search_Result();
65         $sres->results = $jRes->hits->total;
66         $sres->page    = $page;
67         $sres->perPage = $perPage;
68
69         foreach ($jRes->hits->hits as $hit) {
70             $r = new Repository();
71             //FIXME: error handling. what about deleted repos?
72             $r->loadById($hit->_source->id);
73             $sres->repos[] = $r;
74         }
75
76         return $sres;
77     }
78 }
79
80 ?>