Skip to content

Base method toArray processes all constants, including privates. #62

Closed
@marrch-caat

Description

@marrch-caat

Right now, Enum works fine for simple classes, but when I want to add something custom and add some private constants to a class, they are treated as if they were public: they are listed in toArray() output and thus their values make isValid() return TRUE, their names produce TRUE on isValidKey() etc etc. It is very much wrong in many cases.
So I propose the following change:

    public static function toArray()
    {
        $class = get_called_class();
        if (!array_key_exists($class, self::$cache)) {
            $reflection = new \ReflectionClass($class);
-            self::$cache[$class] = $reflection->getConstants();
+            $consts = $reflection->getConstants();
+            self::$cache[$class] = array_filter(
+                $consts,
+                function($v, $k) use($reflection) {
+                    return $reflection->getReflectionConstant($k)->isPublic();
+                }
+            );
        }

        return self::$cache[$class];
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions