HS1993
HS1993

Reputation: 129

php recursive function with reference

I have recursive function with reference param. It goes through the navigation, checking if user is allowed to see current node. But when it goes to the sub-nodes ( $nodeItem['nodes'] ), it works good inside its instance, but doesn't return reduced array. So that's the problem. When it goes to subnodes , where I shouldn't have access, it unsets them in its instance, but when it returns array and I am back in main navigation nodes array, all subnodes are back. What could possibly be wrong?

private function getNodesByRole(&$nodesArray)
{
    foreach ($nodesArray as $nodeKey => $nodeItem) {
        $link = trim($nodeItem['href'], self::SEPARATOR_PRESENTER_LINK);

        if (substr_count($link, self::SEPARATOR_PRESENTER_LINK) == 2) {
            $resource = substr($link, 0, strrpos($link, self::SEPARATOR_PRESENTER_LINK));
            $privilege = substr($link, strrpos($link, self::SEPARATOR_PRESENTER_LINK) + 1);

            if ($this->user->isAllowed($resource, $privilege) === false) {
                unset($nodesArray[$nodeKey]);
                dump($nodeItem);
                dump($nodesArray);
            } else if (!empty($nodeItem['nodes'])) {
                $this->getNodesByRole($nodeItem['nodes']);
            }

        } else {
            if (!empty($nodeItem['nodes'])) {
                $this->getNodesByRole($nodeItem['nodes']);
            }
        }

        if (isset($nodeItem['nodes']) && count($nodeItem['nodes']) == 0) {
            unset($nodesArray[$nodeKey]);
            continue;
        }
    }
    return $nodesArray;
}

Upvotes: 0

Views: 280

Answers (1)

zenwraight
zenwraight

Reputation: 2000

You need to set the returned array to the current states array, like this

private function getNodesByRole(&$nodesArray)
{
foreach ($nodesArray as $nodeKey => $nodeItem) {
    $link = trim($nodeItem['href'], self::SEPARATOR_PRESENTER_LINK);

    if (substr_count($link, self::SEPARATOR_PRESENTER_LINK) == 2) {
        $resource = substr($link, 0, strrpos($link, self::SEPARATOR_PRESENTER_LINK));
        $privilege = substr($link, strrpos($link, self::SEPARATOR_PRESENTER_LINK) + 1);

        if ($this->user->isAllowed($resource, $privilege) === false) {
            unset($nodesArray[$nodeKey]);
            dump($nodeItem);
            dump($nodesArray);
        } else if (!empty($nodeItem['nodes'])) {
            $nodesArray = $this->getNodesByRole($nodeItem['nodes']);
        }

    } else {
        if (!empty($nodeItem['nodes'])) {
            $nodesArray = $this->getNodesByRole($nodeItem['nodes']);
        }
    }

    if (isset($nodeItem['nodes']) && count($nodeItem['nodes']) == 0) {
        unset($nodesArray[$nodeKey]);
        continue;
    }
}
return $nodesArray;
}

Hope it helps!

Upvotes: 1

Related Questions