Clone(duplicate) entity in drupal 7 (commerce orders)

Some throwback to Drupal 7 and commerce or just entities. You need to duplicate(clone) some entity, well you can do it easily with this helper function

function replicate_commerce_entity($entity_type, $id) {
  $original = entity_load_single($entity_type, $id);

  $clone = clone $original;

  // Set the entity as new entity.
  $clone->is_new = TRUE;

  // Reset entity id.
  $entity_info = entity_get_info($entity_type);
  $clone->{$entity_info['entity keys']['id']} = NULL;


  // Reset UUID.
  if (isset($entity_info['uuid']) && $entity_info['uuid'] == TRUE && !empty($entity_info['entity keys']['uuid'])) {
    $clone->{$entity_info['entity keys']['uuid']} = NULL;
    if (!empty($entity_info['entity keys']['revision uuid'])) {
      $clone->{$entity_info['entity keys']['revision uuid']} = NULL;
    }
  }

  // Reset commerce specific ids
  unset($clone->order_number);
  unset($clone->revision_id);
  unset($clone->revision_uid);

  entity_save($entity_type, $clone);

  return $clone;
}

So all you need to do is call this function and you will have a new clone of some entity. Like

$order = replicate_commerce_entity('commerce_order', $order_wrapper->order_id->value());

for non commerce entites part with unseting at the bottom is not needed, also dont forget that this is cloning just entity not entites that are referenced, for example line items in commerce order, for that you would need to loop a bit and have more complex function.