|
| 1 | +//! UnitEnum::cases() return type provider. |
| 2 | +
|
| 3 | +use mago_codex::ttype::atomic::TAtomic; |
| 4 | +use mago_codex::ttype::atomic::array::TArray; |
| 5 | +use mago_codex::ttype::atomic::array::list::TList; |
| 6 | +use mago_codex::ttype::atomic::object::TObject; |
| 7 | +use mago_codex::ttype::atomic::object::r#enum::TEnum; |
| 8 | +use mago_codex::ttype::union::TUnion; |
| 9 | + |
| 10 | +use crate::plugin::context::InvocationInfo; |
| 11 | +use crate::plugin::context::ProviderContext; |
| 12 | +use crate::plugin::provider::Provider; |
| 13 | +use crate::plugin::provider::ProviderMeta; |
| 14 | +use crate::plugin::provider::method::MethodReturnTypeProvider; |
| 15 | +use crate::plugin::provider::method::MethodTarget; |
| 16 | + |
| 17 | +static META: ProviderMeta = |
| 18 | + ProviderMeta::new("php::enum::cases", "UnitEnum::cases", "Returns non-empty-list for enums with at least one case"); |
| 19 | + |
| 20 | +// Use wildcard for class since all enums implement UnitEnum |
| 21 | +static TARGETS: [MethodTarget; 1] = [MethodTarget::any_class("cases")]; |
| 22 | + |
| 23 | +/// Provider for the `UnitEnum::cases()` method. |
| 24 | +/// |
| 25 | +/// Returns `non-empty-list<EnumType>` for enums with at least one case, |
| 26 | +/// or `list<EnumType>` for enums with no cases (edge case). |
| 27 | +#[derive(Default)] |
| 28 | +pub struct EnumCasesProvider; |
| 29 | + |
| 30 | +impl Provider for EnumCasesProvider { |
| 31 | + fn meta() -> &'static ProviderMeta { |
| 32 | + &META |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl MethodReturnTypeProvider for EnumCasesProvider { |
| 37 | + fn targets() -> &'static [MethodTarget] { |
| 38 | + &TARGETS |
| 39 | + } |
| 40 | + |
| 41 | + fn get_return_type( |
| 42 | + &self, |
| 43 | + _context: &ProviderContext<'_, '_, '_>, |
| 44 | + _class_name: &str, |
| 45 | + _method_name: &str, |
| 46 | + invocation_info: &InvocationInfo<'_, '_, '_>, |
| 47 | + ) -> Option<TUnion> { |
| 48 | + let class_metadata = invocation_info.invocation.target.get_method_context()?.class_like_metadata; |
| 49 | + |
| 50 | + if !class_metadata.kind.is_enum() { |
| 51 | + return None; |
| 52 | + } |
| 53 | + |
| 54 | + let enum_type = TUnion::from_atomic(TAtomic::Object(TObject::Enum(TEnum { |
| 55 | + name: class_metadata.original_name, |
| 56 | + case: None, |
| 57 | + }))); |
| 58 | + |
| 59 | + if !class_metadata.enum_cases.is_empty() { |
| 60 | + Some(TUnion::from_atomic(TAtomic::Array(TArray::List(TList::new_non_empty(Box::new(enum_type)))))) |
| 61 | + } else { |
| 62 | + Some(TUnion::from_atomic(TAtomic::Array(TArray::List(TList::new(Box::new(enum_type)))))) |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments