1use crate::codegen;
37use crate::php::{self, CallStep};
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Relation {
41 BelongsTo {
42 method: String,
43 related: String,
44 foreign_key: String,
45 inferred: bool,
46 },
47 HasMany {
48 method: String,
49 related: String,
50 foreign_key: String,
51 inferred: bool,
52 },
53 HasOne {
54 method: String,
55 related: String,
56 foreign_key: String,
57 inferred: bool,
58 },
59 BelongsToMany {
60 method: String,
61 related: String,
62 through: String,
63 foreign_key: String,
64 related_pivot_key: String,
65 inferred_through: bool,
66 inferred_foreign_key: bool,
67 inferred_related_pivot_key: bool,
68 },
69}
70
71pub fn parse_relation(
80 declaring_class: &str,
81 method_name: &str,
82 body: tree_sitter::Node,
83 source: &str,
84) -> Result<Option<Relation>, String> {
85 let statements = php::direct_children_of_kind(body, "return_statement");
86 if statements.len() != 1 {
87 return Ok(None);
88 }
89 let Some(expr) = php::return_expression(statements[0]) else {
90 return Ok(None);
91 };
92 let Some(chain) = php::walk_call_chain(expr, source) else {
93 return Ok(None);
94 };
95 let [step]: [CallStep; 1] = chain.try_into().map_err(|_| {
97 format!("{method_name}(): relationship call is chained with something else, not supported")
98 })?;
99
100 let related = step
101 .args
102 .first()
103 .and_then(|arg| arg.strip_suffix("::class"))
104 .map(str::trim)
105 .ok_or_else(|| format!("{method_name}(): no related model class found"))?
106 .to_string();
107
108 match step.method.as_str() {
109 "belongsTo" => {
110 let (foreign_key, inferred) = match step.args.get(1) {
111 Some(fk) => (php::unquote(fk), false),
112 None => (format!("{}_id", codegen::to_snake_case(method_name)), true),
113 };
114 Ok(Some(Relation::BelongsTo {
115 method: method_name.to_string(),
116 related,
117 foreign_key,
118 inferred,
119 }))
120 }
121 "hasMany" | "hasOne" => {
122 let (foreign_key, inferred) = match step.args.get(1) {
123 Some(fk) => (php::unquote(fk), false),
124 None => (
125 format!("{}_id", codegen::to_snake_case(declaring_class)),
126 true,
127 ),
128 };
129 let relation = if step.method == "hasMany" {
130 Relation::HasMany {
131 method: method_name.to_string(),
132 related,
133 foreign_key,
134 inferred,
135 }
136 } else {
137 Relation::HasOne {
138 method: method_name.to_string(),
139 related,
140 foreign_key,
141 inferred,
142 }
143 };
144 Ok(Some(relation))
145 }
146 "belongsToMany" => {
147 let (through, inferred_through) = match step.args.get(1) {
148 Some(t) => (php::unquote(t), false),
149 None => (default_pivot_table(&related, declaring_class), true),
150 };
151 let (foreign_key, inferred_foreign_key) = match step.args.get(2) {
152 Some(fk) => (php::unquote(fk), false),
153 None => (
154 format!("{}_id", codegen::to_snake_case(declaring_class)),
155 true,
156 ),
157 };
158 let (related_pivot_key, inferred_related_pivot_key) = match step.args.get(3) {
159 Some(rk) => (php::unquote(rk), false),
160 None => (format!("{}_id", codegen::to_snake_case(&related)), true),
161 };
162 Ok(Some(Relation::BelongsToMany {
163 method: method_name.to_string(),
164 related,
165 through,
166 foreign_key,
167 related_pivot_key,
168 inferred_through,
169 inferred_foreign_key,
170 inferred_related_pivot_key,
171 }))
172 }
173 other => Err(format!(
174 "{method_name}(): `{other}` isn't a supported relationship type"
175 )),
176 }
177}
178
179pub fn related_type_name(relation: &Relation) -> &str {
185 match relation {
186 Relation::BelongsTo { related, .. }
187 | Relation::HasMany { related, .. }
188 | Relation::HasOne { related, .. }
189 | Relation::BelongsToMany { related, .. } => related,
190 }
191}
192
193pub fn method_name(relation: &Relation) -> &str {
197 match relation {
198 Relation::BelongsTo { method, .. }
199 | Relation::HasMany { method, .. }
200 | Relation::HasOne { method, .. }
201 | Relation::BelongsToMany { method, .. } => method,
202 }
203}
204
205fn default_pivot_table(related: &str, declaring: &str) -> String {
209 let mut names = [
210 codegen::to_snake_case(related),
211 codegen::to_snake_case(declaring),
212 ];
213 names.sort();
214 names.join("_")
215}
216
217pub fn render(relation: &Relation) -> String {
222 match relation {
223 Relation::BelongsTo {
224 related,
225 foreign_key,
226 inferred,
227 ..
228 } => with_inferred_comment(
229 *inferred,
230 format!("#[belongs_to({related}, foreign_key = \"{foreign_key}\")]"),
231 ),
232 Relation::HasMany {
233 related,
234 foreign_key,
235 inferred,
236 ..
237 } => with_inferred_comment(
238 *inferred,
239 format!("#[has_many({related}, foreign_key = \"{foreign_key}\")]"),
240 ),
241 Relation::HasOne {
242 related,
243 foreign_key,
244 inferred,
245 ..
246 } => with_inferred_comment(
247 *inferred,
248 format!("#[has_one({related}, foreign_key = \"{foreign_key}\")]"),
249 ),
250 Relation::BelongsToMany {
251 related,
252 through,
253 foreign_key,
254 related_pivot_key,
255 inferred_through,
256 inferred_foreign_key,
257 inferred_related_pivot_key,
258 ..
259 } => with_inferred_comment(
260 *inferred_through || *inferred_foreign_key || *inferred_related_pivot_key,
261 format!(
262 "#[belongs_to_many({related}, through = \"{through}\", foreign_key = \"{foreign_key}\", related_pivot_key = \"{related_pivot_key}\")]"
263 ),
264 ),
265 }
266}
267
268fn with_inferred_comment(inferred: bool, attribute: String) -> String {
269 if inferred {
270 format!("// inferred from Laravel's default naming convention - verify\n{attribute}")
271 } else {
272 attribute
273 }
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279 use crate::php;
280
281 fn parse_method_relation(
282 source: &str,
283 class: &str,
284 method: &str,
285 ) -> Result<Option<Relation>, String> {
286 let tree = php::parse(source).unwrap();
287 let method_node = php::find_method(&tree, source, class, method).unwrap();
288 let body = method_node.child_by_field_name("body").unwrap();
289 parse_relation(class, method, body, source)
290 }
291
292 #[test]
293 fn belongs_to_uses_explicit_foreign_key_verbatim() {
294 let source = "<?php\nclass Post {\n public function author(): BelongsTo\n {\n return $this->belongsTo(User::class, 'user_id');\n }\n}\n";
295 let relation = parse_method_relation(source, "Post", "author")
296 .unwrap()
297 .unwrap();
298 assert_eq!(
299 relation,
300 Relation::BelongsTo {
301 method: "author".to_string(),
302 related: "User".to_string(),
303 foreign_key: "user_id".to_string(),
304 inferred: false,
305 }
306 );
307 }
308
309 #[test]
310 fn belongs_to_infers_foreign_key_from_the_method_name_not_the_related_class() {
311 let source = "<?php\nclass Post {\n public function editor(): BelongsTo\n {\n return $this->belongsTo(User::class);\n }\n}\n";
312 let relation = parse_method_relation(source, "Post", "editor")
313 .unwrap()
314 .unwrap();
315 assert_eq!(
316 relation,
317 Relation::BelongsTo {
318 method: "editor".to_string(),
319 related: "User".to_string(),
320 foreign_key: "editor_id".to_string(),
321 inferred: true,
322 }
323 );
324 }
325
326 #[test]
327 fn has_many_infers_foreign_key_from_the_declaring_class() {
328 let source = "<?php\nclass User {\n public function posts(): HasMany\n {\n return $this->hasMany(Post::class);\n }\n}\n";
329 let relation = parse_method_relation(source, "User", "posts")
330 .unwrap()
331 .unwrap();
332 assert_eq!(
333 relation,
334 Relation::HasMany {
335 method: "posts".to_string(),
336 related: "Post".to_string(),
337 foreign_key: "user_id".to_string(),
338 inferred: true,
339 }
340 );
341 }
342
343 #[test]
344 fn belongs_to_many_infers_pivot_table_and_both_keys_when_all_omitted() {
345 let source = "<?php\nclass Post {\n public function tags(): BelongsToMany\n {\n return $this->belongsToMany(Tag::class);\n }\n}\n";
346 let relation = parse_method_relation(source, "Post", "tags")
347 .unwrap()
348 .unwrap();
349 assert_eq!(
350 relation,
351 Relation::BelongsToMany {
352 method: "tags".to_string(),
353 related: "Tag".to_string(),
354 through: "post_tag".to_string(),
355 foreign_key: "post_id".to_string(),
356 related_pivot_key: "tag_id".to_string(),
357 inferred_through: true,
358 inferred_foreign_key: true,
359 inferred_related_pivot_key: true,
360 }
361 );
362 }
363
364 #[test]
365 fn belongs_to_many_uses_explicit_pivot_table_and_keys_verbatim() {
366 let source = "<?php\nclass Post {\n public function categories(): BelongsToMany\n {\n return $this->belongsToMany(Category::class, 'category_post', 'post_id', 'category_id');\n }\n}\n";
367 let relation = parse_method_relation(source, "Post", "categories")
368 .unwrap()
369 .unwrap();
370 assert_eq!(
371 relation,
372 Relation::BelongsToMany {
373 method: "categories".to_string(),
374 related: "Category".to_string(),
375 through: "category_post".to_string(),
376 foreign_key: "post_id".to_string(),
377 related_pivot_key: "category_id".to_string(),
378 inferred_through: false,
379 inferred_foreign_key: false,
380 inferred_related_pivot_key: false,
381 }
382 );
383 }
384
385 #[test]
386 fn an_unsupported_relationship_type_is_flagged() {
387 let source = "<?php\nclass Post {\n public function comments()\n {\n return $this->hasManyThrough(Comment::class, User::class);\n }\n}\n";
388 let err = parse_method_relation(source, "Post", "comments").unwrap_err();
389 assert!(err.contains("hasManyThrough"));
390 }
391
392 #[test]
393 fn a_non_relationship_method_is_skipped_not_flagged() {
394 let source = "<?php\nclass Post {\n public function getExcerpt(): string\n {\n return substr($this->content, 0, 100);\n }\n}\n";
395 let result = parse_method_relation(source, "Post", "getExcerpt").unwrap();
396 assert!(result.is_none());
397 }
398
399 #[test]
400 fn render_adds_an_inferred_comment_only_when_something_was_inferred() {
401 let explicit = Relation::BelongsTo {
402 method: "author".to_string(),
403 related: "User".to_string(),
404 foreign_key: "user_id".to_string(),
405 inferred: false,
406 };
407 assert!(!render(&explicit).contains("inferred"));
408
409 let inferred = Relation::BelongsTo {
410 method: "editor".to_string(),
411 related: "User".to_string(),
412 foreign_key: "editor_id".to_string(),
413 inferred: true,
414 };
415 assert!(render(&inferred).contains("inferred from Laravel's default naming convention"));
416 }
417}