Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

96
Views
PHP Specific optimization for if loop in Symfony

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 ?

10 months ago · Santiago Trujillo
1 answers
Answer question

0

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.

10 months ago · Santiago Trujillo Report
Answer question
Find remote jobs