sqry-cli 9.0.20

CLI for sqry - semantic code search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
//! CLI integration tests for PHP relation queries
//!
//! Tests that relation queries work end-to-end through the CLI for PHP:
//! - Callers queries (instance methods, static methods, functions)
//! - Callees queries (what a function calls)
//! - Exports queries (classes, methods with visibility filtering)
//! - Imports queries (use statements, require)
//!
//! This validates the PHP relation extraction implementation against the
//! ≥95% recall target (M1, M2, M3 from docs/development/relation-tracking/php/01_SPEC.md).

mod common;
use common::sqry_bin;

use assert_cmd::Command;
use predicates::prelude::*;
use serial_test::serial;
use std::path::Path;
use tempfile::TempDir;

// ============================================================================
// Callers Queries - Instance and Static Method Calls
// ============================================================================

#[test]
fn cli_php_callers_instance_methods() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
class UserService {
    public function authenticate($username, $password) {
        $user = $this->findUser($username);
        if ($user) {
            return $this->validatePassword($user, $password);
        }
        return false;
    }

    private function findUser($username) {
        return Database::query('SELECT * FROM users WHERE username = ?', [$username]);
    }

    private function validatePassword($user, $password) {
        return password_verify($password, $user->password_hash);
    }
}

class Database {
    public static function query($sql, $params = []) {
        return null;
    }
}
";
    std::fs::write(project.path().join("UserService.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of findUser (private method)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:findUser")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("authenticate"));

    // Query for callers of validatePassword (private method)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:validatePassword")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("authenticate"));
}

#[test]
fn cli_php_callers_static_methods() {
    let project = TempDir::new().unwrap();

    let php_code = r#"<?php
class Logger {
    public static function info($message) {
        self::write('INFO', $message);
    }

    public static function error($message) {
        self::write('ERROR', $message);
    }

    private static function write($level, $message) {
        echo "[$level] $message\n";
    }
}

class Application {
    public function run() {
        Logger::info('Application started');
        Logger::error('Something went wrong');
    }
}
"#;
    std::fs::write(project.path().join("Logger.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of Logger::info
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:info")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("run"));

    // Query for callers of Logger::error
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:error")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("run"));

    // Query for callers of write (called by info and error via self::)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:write")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("info"))
        .stdout(predicate::str::contains("error"));
}

#[test]
fn cli_php_callers_global_functions() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

function normalizeUsername($username) {
    return trim(strtolower($username));
}

function processUserInput($username, $email) {
    $username = normalizeUsername($username);
    $valid = validateEmail($email);
    return $valid;
}
";
    std::fs::write(project.path().join("helpers.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of validateEmail
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:validateEmail")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("processUserInput"));

    // Query for callers of normalizeUsername
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:normalizeUsername")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("processUserInput"));
}

#[test]
fn cli_php_callers_namespaced_functions() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
namespace App\Helpers;

function slugify($text) {
    return strtolower(preg_replace('/[^a-z0-9]+/', '-', $text));
}

function truncate($text, $length = 100) {
    return strlen($text) > $length ? substr($text, 0, $length) . '...' : $text;
}

namespace App\Services;

use function App\Helpers\slugify;

class PostService {
    public function createSlug($title) {
        return slugify($title);
    }
}
";
    std::fs::write(project.path().join("services.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of slugify
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:slugify")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("createSlug"));
}

#[test]
fn cli_php_callers_null_safe_operator() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
class User {
    private $profile;

    public function getProfile() {
        return $this->profile;
    }
}

class Profile {
    private $name;

    public function getName() {
        return $this->name;
    }
}

class UserService {
    public function getUserName($user) {
        return $user?->getProfile()?->getName();
    }
}
";
    std::fs::write(project.path().join("user.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of getProfile (called via null-safe operator)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:getProfile")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("getUserName"));

    // Query for callers of getName (called via null-safe operator)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:getName")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("getUserName"));
}

// ============================================================================
// Exports Queries - Classes, Methods, Visibility
// ============================================================================

#[test]
fn cli_php_exports_classes_and_interfaces() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
class User {
    public function getId() {
        return $this->id;
    }
}

interface Repository {
    public function findById($id);
    public function save($entity);
}

class UserRepository implements Repository {
    public function findById($id) {
        return null;
    }

    public function save($entity) {
        return true;
    }
}

trait Timestampable {
    public function getCreatedAt() {
        return $this->created_at;
    }
}
";
    std::fs::write(project.path().join("models.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for User class export
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:User")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("models.php"));

    // Query for Repository interface export
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:Repository")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("models.php"));

    // Query for Timestampable trait export
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:Timestampable")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("models.php"));
}

#[test]

fn cli_php_exports_visibility_filtering() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
class UserService {
    public function createUser($username, $password) {
        $this->validateInput($username, $password);
        $hash = $this->hashPassword($password);
        return true;
    }

    public function updateUser($id, $data) {
        return true;
    }

    protected function validateInput($username, $password) {
        return true;
    }

    private function hashPassword($password) {
        return password_hash($password, PASSWORD_DEFAULT);
    }
}
";
    std::fs::write(project.path().join("UserService.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for createUser (public method - should be exported)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:createUser")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("UserService.php"));

    // Query for updateUser (public method - should be exported)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:updateUser")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("UserService.php"));

    // Protected/private methods should not be exported
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:validateInput")
        .arg(project.path())
        .assert()
        .success()
        .stderr(predicate::str::contains("No matches found"));

    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:hashPassword")
        .arg(project.path())
        .assert()
        .success()
        .stderr(predicate::str::contains("No matches found"));
}

#[test]

fn cli_php_exports_namespaced_classes() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
namespace App\Services;

class UserService {
    public function getUsers() {
        return [];
    }
}

namespace App\Repositories;

class UserRepository {
    public function findAll() {
        return [];
    }
}
";
    std::fs::write(project.path().join("app.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for UserService (should find namespace-qualified export)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:UserService")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("app.php"));

    // Query for UserRepository (should find namespace-qualified export)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:UserRepository")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("app.php"));
}

#[test]
fn cli_php_exports_global_functions() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
function globalHelper() {
    return true;
}

namespace App\Helpers;

function namespacedHelper() {
    return true;
}
";
    std::fs::write(project.path().join("functions.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for globalHelper (global function export)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:globalHelper")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("functions.php"));

    // Query for namespacedHelper (namespaced function export)
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:namespacedHelper")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("functions.php"));
}

// ============================================================================
// Imports Queries - use statements, require
// ============================================================================

#[test]
fn cli_php_imports_use_statements() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
namespace App\Controllers;

use App\Services\UserService;
use App\Repositories\UserRepository;

class UserController {
    private $userService;

    public function __construct(UserService $service) {
        $this->userService = $service;
    }

    public function index() {
        return $this->userService->getUsers();
    }
}
";
    std::fs::write(project.path().join("UserController.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for imports of UserService
    Command::new(sqry_bin())
        .arg("query")
        .arg("imports:UserService")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("UserController.php"));

    // Query for imports of UserRepository
    Command::new(sqry_bin())
        .arg("query")
        .arg("imports:UserRepository")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("UserController.php"));
}

#[test]
fn cli_php_imports_require_statements() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
require_once 'config.php';
require_once __DIR__ . '/helpers.php';
include 'optional.php';

class Application {
    public function run() {
        return true;
    }
}
";
    std::fs::write(project.path().join("app.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for imports of config.php
    Command::new(sqry_bin())
        .arg("query")
        .arg("imports:config")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("app.php"));

    // Query for imports of helpers.php
    Command::new(sqry_bin())
        .arg("query")
        .arg("imports:helpers")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("app.php"));
}

// ============================================================================
// Callees Queries - What a function calls
// ============================================================================

#[test]
fn cli_php_callees_query() {
    let project = TempDir::new().unwrap();

    let php_code = r#"<?php
class UserService {
    public function authenticate($username, $password) {
        $user = $this->findUser($username);
        $valid = $this->validatePassword($user, $password);
        $this->logAttempt($username, $valid);
        return $valid;
    }

    private function findUser($username) {
        return null;
    }

    private function validatePassword($user, $password) {
        return password_verify($password, $user->password);
    }

    private function logAttempt($username, $success) {
        error_log("Login attempt: $username");
    }
}
"#;
    std::fs::write(project.path().join("UserService.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callees of authenticate (what authenticate calls)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callees:authenticate")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("findUser"))
        .stdout(predicate::str::contains("validatePassword"))
        .stdout(predicate::str::contains("logAttempt"));
}

// ============================================================================
// Method Chaining Patterns
// ============================================================================

#[test]
fn cli_php_callers_method_chaining() {
    let project = TempDir::new().unwrap();

    let php_code = r"<?php
class QueryBuilder {
    public function table($table) {
        return $this;
    }

    public function where($column, $value) {
        return $this;
    }

    public function orderBy($column) {
        return $this;
    }

    public function get() {
        return [];
    }
}

class UserQuery {
    private $builder;

    public function __construct() {
        $this->builder = new QueryBuilder();
    }

    public function findActiveUsers() {
        return $this->builder
            ->table('users')
            ->where('status', 'active')
            ->orderBy('created_at')
            ->get();
    }
}
";
    std::fs::write(project.path().join("QueryBuilder.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of table (first in chain)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:table")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("findActiveUsers"));

    // Query for callers of where (middle of chain)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:where")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("findActiveUsers"));

    // Query for callers of get (end of chain)
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:get")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("findActiveUsers"));
}

// JSON OUTPUT TESTS (validates --json flag and PHP-specific metadata)

#[test]
fn cli_php_json_exports_with_methods() {
    // Test that exports: query correctly finds class and methods
    // Note: exports:ClassName finds the class; exports:methodName finds methods
    let project = TempDir::new().unwrap();
    let php_code = r"<?php
namespace App\Services;

class UserService {
    public function authenticate($username, $password) {
        return $this->findUser($username);
    }

    private function findUser($username) {
        return null;
    }

    protected function validatePassword($password) {
        return strlen($password) >= 8;
    }
}
";
    std::fs::write(project.path().join("UserService.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // exports:UserService finds the class
    let output = Command::new(sqry_bin())
        .arg("query")
        .arg("exports:UserService")
        .arg("--json")
        .arg(project.path())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json_str = String::from_utf8(output).expect("valid UTF-8");
    let json: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

    let results = json["results"].as_array().expect("results should be array");
    assert!(
        !results.is_empty(),
        "exports:UserService should find the class"
    );

    // The class should be found
    let class_result = results
        .iter()
        .find(|r| {
            r["name"]
                .as_str()
                .is_some_and(|n| n.contains("UserService"))
        })
        .expect("Should find UserService class");

    assert_eq!(
        class_result["kind"].as_str(),
        Some("class"),
        "Result should be a class"
    );

    // exports:authenticate finds the public method
    let output = Command::new(sqry_bin())
        .arg("query")
        .arg("exports:authenticate")
        .arg("--json")
        .arg(project.path())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json_str = String::from_utf8(output).expect("valid UTF-8");
    let json: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

    let results = json["results"].as_array().expect("results should be array");
    assert!(
        !results.is_empty(),
        "exports:authenticate should find the public method"
    );

    // Verify the method is found with qualified name
    let method_result = results
        .iter()
        .find(|r| {
            r["qualified_name"]
                .as_str()
                .is_some_and(|n| n.contains("authenticate"))
        })
        .expect("Should find authenticate method");

    assert_eq!(
        method_result["kind"].as_str(),
        Some("method"),
        "Result should be a method"
    );
}

#[test]
fn cli_php_json_calls_with_dynamic_metadata() {
    let project = TempDir::new().unwrap();
    let php_code = r#"<?php
namespace App\Services;

class EventDispatcher {
    public function dispatch($eventName, $data) {
        // Dynamic call via call_user_func
        $handler = $this->getHandler($eventName);
        call_user_func($handler, $data);

        // Regular static method call
        Logger::info("Event dispatched: " . $eventName);
    }

    private function getHandler($eventName) {
        return 'handleEvent';
    }
}
"#;
    std::fs::write(project.path().join("EventDispatcher.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    let output = Command::new(sqry_bin())
        .arg("query")
        .arg("callers:call_user_func")
        .arg("--json")
        .arg(project.path())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let json_str = String::from_utf8(output).expect("valid UTF-8");
    let json: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

    // Verify results exist
    let results = json["results"].as_array().expect("results should be array");

    // For call_user_func, we expect to find it as a called function
    // The structure may have the call location info
    // Note: The exact metadata structure for dynamic calls may vary
    // This test validates that --json mode works and structure is correct

    // At minimum, verify the JSON structure is valid
    assert!(json.get("query").is_some(), "JSON should have 'query' key");
    assert!(json.get("stats").is_some(), "JSON should have 'stats' key");

    // If we have results, they should have proper structure
    if !results.is_empty() {
        let first_result = &results[0];
        assert!(
            first_result.get("file_path").is_some(),
            "Result should have file_path"
        );
        assert!(
            first_result.get("start_line").is_some(),
            "Result should have start_line"
        );
    }
}

// NEGATIVE TEST CASES (error handling and edge cases)

#[test]
fn cli_php_callers_query_no_results() {
    let project = TempDir::new().unwrap();
    let php_code = r"<?php
class Foo {
    public function bar() {
        return 42;
    }
}
";
    std::fs::write(project.path().join("Foo.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for callers of a function that is never called
    let output = Command::new(sqry_bin())
        .arg("query")
        .arg("callers:nonexistent")
        .arg(project.path())
        .assert()
        .success();

    // Should return successfully with no results
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);
    assert!(
        stdout.contains("No results") || stdout.is_empty() || stdout.trim().is_empty(),
        "Should indicate no results when querying for non-existent symbol"
    );
}

#[test]
fn cli_php_exports_empty_class() {
    let project = TempDir::new().unwrap();
    let php_code = r"<?php
class EmptyClass {
    // No methods
}
";
    std::fs::write(project.path().join("Empty.php"), php_code).unwrap();

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query for exports of empty class
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:EmptyClass")
        .arg(project.path())
        .assert()
        .success();
    // Should succeed even with empty results
}

#[test]
fn cli_php_callers_syntax_error_file() {
    let project = TempDir::new().unwrap();

    // Create a valid PHP file first
    let valid_php = r"<?php
class Valid {
    public function test() {
        return 1;
    }
}
";
    std::fs::write(project.path().join("Valid.php"), valid_php).unwrap();

    // Create a file with syntax error
    let invalid_php = r"<?php
class Invalid {
    public function broken( {  // Syntax error
        return 1;
    }
}
";
    std::fs::write(project.path().join("Invalid.php"), invalid_php).unwrap();

    // Index should succeed but skip invalid file
    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Query should still work on valid files
    // exports:Valid finds the class named "Valid", not its methods
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:Valid")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("Valid"));
}

// FIXTURE-BASED RECALL TESTS (ground truth validation)

#[test]
#[serial]
fn cli_php_fixture_symfony_exports_recall() {
    // Use symfony_controller.php fixture with ground truth annotations
    // Test verifies that class and methods are exported correctly
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("sqry-lang-php/tests/fixtures/relations/php/integration");

    // Ensure stale indexes do not interfere with validation
    let _ = std::fs::remove_dir_all(fixture_path.join(".sqry-index"));
    let _ = std::fs::remove_file(fixture_path.join(".sqry-index"));
    let _ = std::fs::remove_file(fixture_path.join(".sqry-index.trg"));
    let _ = std::fs::remove_dir_all(fixture_path.join(".sqry-cache"));

    // Index the fixture directory
    Command::new(sqry_bin())
        .arg("index")
        .arg(&fixture_path)
        .assert()
        .success();

    // Verify the UserController class is exported
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:UserController")
        .arg(&fixture_path)
        .assert()
        .success()
        .stdout(predicate::str::contains("UserController"));

    // Verify key methods are exported by querying each directly
    // Ground truth methods: index, show, create, edit, delete, search
    let expected_methods = vec!["index", "show", "create", "edit", "delete", "search"];
    let mut found_count = 0;

    for method in &expected_methods {
        let output = Command::new(sqry_bin())
            .arg("query")
            .arg(format!("exports:{method}"))
            .arg(&fixture_path)
            .output()
            .expect("command should run");

        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout.contains(method) {
            found_count += 1;
        }
    }

    // Recall test: Should find at least 5 out of 6 key method exports (>80% recall)
    assert!(
        found_count >= 5,
        "Expected to find at least 5/6 exported methods, found {found_count}. Expected: {expected_methods:?}"
    );
}

#[test]
#[serial]
fn cli_php_fixture_symfony_callers_recall() {
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("sqry-lang-php/tests/fixtures/relations/php/integration");

    // Ensure stale indexes do not interfere with validation
    let _ = std::fs::remove_dir_all(fixture_path.join(".sqry-index"));
    let _ = std::fs::remove_file(fixture_path.join(".sqry-index"));
    let _ = std::fs::remove_file(fixture_path.join(".sqry-index.trg"));
    let _ = std::fs::remove_dir_all(fixture_path.join(".sqry-cache"));

    Command::new(sqry_bin())
        .arg("index")
        .arg(&fixture_path)
        .assert()
        .success();

    // Query for callers of render (common method called in many controller actions)
    // Ground truth from annotations: render is called in index, show, create, edit actions
    let output = Command::new(sqry_bin())
        .arg("query")
        .arg("callers:render")
        .arg(&fixture_path)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(output).expect("valid UTF-8");

    // Should find multiple callers (index, show, create, edit)
    let expected_callers = vec!["index", "show", "create", "edit"];
    let mut found_count = 0;

    for caller in &expected_callers {
        if stdout.contains(caller) {
            found_count += 1;
        }
    }

    // Recall test: Should find at least 3 out of 4 callers (75% recall minimum)
    assert!(
        found_count >= 3,
        "Expected to find at least 3/4 callers of render, found {found_count}"
    );
}

#[test]
fn cli_php_fixture_laravel_comprehensive() {
    // Verify the laravel_service.php fixture works end-to-end
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("sqry-lang-php/tests/fixtures/relations/php/integration/laravel_service.php");

    // Create temp dir and copy fixture
    let project = TempDir::new().unwrap();
    std::fs::copy(&fixture_path, project.path().join("laravel_service.php")).expect("copy fixture");

    Command::new(sqry_bin())
        .arg("index")
        .arg(project.path())
        .assert()
        .success();

    // Test exports query - exports:UserService finds the class named UserService
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:UserService")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("UserService"));

    // Test exports query for a method - exports:createUser finds the method
    Command::new(sqry_bin())
        .arg("query")
        .arg("exports:createUser")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("createUser"));

    // Test callers query - validateUserData is called by createUser
    Command::new(sqry_bin())
        .arg("query")
        .arg("callers:validateUserData")
        .arg(project.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("createUser"));
}