mago_codex/
visibility.rs

1use serde::Deserialize;
2use serde::Serialize;
3
4use mago_syntax::ast::Modifier;
5
6/// Represents the visibility level of class members (properties, methods, constants) in PHP.
7#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default, PartialOrd, Ord)]
8#[repr(u8)]
9pub enum Visibility {
10    /// Represents `public` visibility. Accessible from anywhere.
11    /// This is the default visibility in PHP if none is specified.
12    #[default]
13    Public,
14    /// Represents `protected` visibility. Accessible only within the declaring class,
15    /// its parent classes, and inheriting classes.
16    Protected,
17    /// Represents `private` visibility. Accessible only within the declaring class.
18    Private,
19}
20
21impl Visibility {
22    /// Checks if the visibility level is `Public`.
23    #[inline]
24    pub const fn is_public(&self) -> bool {
25        matches!(self, Visibility::Public)
26    }
27
28    /// Checks if the visibility level is `Protected`.
29    #[inline]
30    pub const fn is_protected(&self) -> bool {
31        matches!(self, Visibility::Protected)
32    }
33
34    /// Checks if the visibility level is `Private`.
35    #[inline]
36    pub const fn is_private(&self) -> bool {
37        matches!(self, Visibility::Private)
38    }
39
40    /// Returns the visibility level as a static string.
41    #[inline]
42    pub const fn as_str(&self) -> &'static str {
43        match self {
44            Visibility::Public => "public",
45            Visibility::Protected => "protected",
46            Visibility::Private => "private",
47        }
48    }
49}
50
51/// Formats the visibility level as the corresponding lowercase PHP keyword.
52impl std::fmt::Display for Visibility {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "{}", self.as_str())
55    }
56}
57
58/// Attempts to convert an AST `Modifier` node into a `Visibility` level.
59impl TryFrom<&Modifier<'_>> for Visibility {
60    type Error = ();
61
62    fn try_from(value: &Modifier<'_>) -> Result<Self, Self::Error> {
63        match value {
64            Modifier::Public(_) | Modifier::PublicSet(_) => Ok(Visibility::Public),
65            Modifier::Protected(_) | Modifier::ProtectedSet(_) => Ok(Visibility::Protected),
66            Modifier::Private(_) | Modifier::PrivateSet(_) => Ok(Visibility::Private),
67            _ => Err(()),
68        }
69    }
70}