Home > Software design >  PHP Specific optimization for if loop in Symfony
PHP Specific optimization for if loop in Symfony

Time:11-24

In Symfony app, i need to use switch/case function, but request parameters prevents me, and i use an uggly if condition like :

        $roles = ["ROLE_USER"];

        if ($request->get('isAdmin')) {
            array_push($roles, "ROLE_ADMIN");
        }

        if ($request->get('isFreemium')) {
            array_push($roles, "ROLE_FREEMIUM");
        }

        if ($request->get('isPremium')) {
            array_push($roles, "ROLE_PREMIUM");
        }

        if ($request->get('isExternal')) {
            array_push($roles, "ROLE_EXTERNAL");
        }

        if ($request->get('isVip')) {
            array_push($roles, "ROLE_VIP");
        }

Can you help me to simplify it ?

CodePudding user response:

You can try the following.

$definedRoles = new ArrayObject([
    'Admin',
    'Freemium',
    'Premium',
    'External',
    'Vip',
]);

$roles = new ArrayObject([ 'ROLE_USER' ]);

foreach ($definedRoles as $role) {
    if ($request->get('is' . $role)) {
        $roles->append(strtoupper('role_' . $role));
    }
}

Why I 'm using the ArrayObject class? Because it works like a yield already. Unlike an array, the object occupies memory only for the current entry when iterated. Thus your loop occupies little memory and you do not load all entries into the memory.

Put all your valid roles into the first array $definedRoles. All the roles will be iterated and an if condition will check, if it 's in the $request object. If so, the role will be appended to the $roles array.

  • Related