Debugging By Dumping

By now, most of us will likely have used the dump($var); function made available for us in Symfony 2.6.

If you haven’t, or you think you can’t because you a) don’t have the latest and greatest version of Symfony, or b) don’t use Symfony, then never fear, you can include the VarDumper component in any project. No excuses.

Whilst the  dump($var); function is incredibly useful, in one instance so far, it has caused me more headaches than it has solved.

The Situation

I’m working on a new RESTful API using Symfony 2 as my back end.

Along the way, I want to restrict Users from being able to access other peoples data, for obvious reasons.

Without getting too deep into the code – as it’s really not that important to this problem / solution – I hit upon an issue where I wasn’t getting the expected output. Such is life of a developer.

However, I can tell you are getting twitchy from having not yet seen any code, so to placate your code cravings, here is the method:

    /**
     * @return array
     */
    public function findAll()
    {
        $accounts = $this->repository->findAll();

        foreach ($accounts as $account) {
            $this->denyAccessUnlessGranted('view', $account);
        }

        return $accounts;
    }

See, I told you, not much to look at.

At some point along the way (and in truth, I haven’t figured out exactly where as of yet), I know that $this->denyAccessUnlessGranted(‘view’, $account);  is having a bad time.

To begin with, I wanted to see exactly what the contents of $accounts was before it even hit the foreach loop.

To the dumper!

    /**
     * @return array
     */
    public function findAll()
    {
        $accounts = $this->repository->findAll();

        exit(dump($accounts));

        foreach ($accounts as $account) {
            $this->denyAccessUnlessGranted('view', $account);
        }

        return $accounts;
    }

Alas, no:

the-output-of-symfony-vardumper-dump

The next thing you might think is – ok, just use print_r($var); and be done with it.

Unfortunately, that’s not an option when dealing with most Doctrine entities. If you try, you may get lucky, you may hit funky maximum nesting level errors, or worse, you may crash your DHC client. Guess which I encountered?

My Solution

Never the less, there is a solution. Quite an old school solution. Something I used to use all the time before the VarDumper component was a thing:

exit(\Doctrine\Common\Util\Debug::dump($yourVariableHere));

This will give you an equivalent of print_r($var); but without the nasty blow ups:

the-output-of-doctrine-dump

It’s an old technique sir, but it checks out.

Now just to figure out why the test is failing, and everything will be right with the world once more.