Making field collections play nice with hook_node_presave

Field Collections are basically multifields in Drupal 7. They're so much user-friendlier than having referenced nodes, and so much lighter. However, if you try to add items to them (that is, an unlimited field collection field) in hook_node_presave , you get stuck in an endless loop. If you have XDebug or similar, you will see the extremely unhelpful message " Maximum function nesting level of '100' reached, aborting!". So what now?

First, you need to understand the root of the problem: when adding an item to the field collection, you are indirectly invoking node_save() (via entity_save() ), which invokes hook_node_presave, which calls your code again. 

In my case, I wanted to process a CSV file, and populate the field collection with some math results based on that (the CSV was a phone bill, the field collection people who were splitting the bill, with fields for the amount owed by each).

So after adding a row to the field collection, saving that item lead to me re-adding that same row in a different invocation of my hook. Not nice.

The only solution I could find, albeit hacky, works like a charm: add a static flag to your hook to check if it already running.

function mymodule_node_presave($node) {
  static $hook_running=false;
  if($hook_running) {
    return;
  } else {
    $hook_runnin=true;
  }

  // ... Actual code goes here ...

  $running = false;
}

And viola! We're done. If anyone knows of a better way to go around this issue, I'll be glad to head about it!