Skip to main content

mago_codex/
visibility.rs

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