def _handle_transform_replacements(document, link, link_ancestors):
    """
    Given a new document, and the link/ancestors it was created,
    determine if we should:
    * Make an inline replacement and then return the modified document tree.
    * Return the new document as-is.
    """
    if link.transform is None:
        transform = link.action.lower() in ('put', 'patch', 'delete')
    else:
        transform = link.transform

    if transform:
        root = link_ancestors[0].document
        keys_to_link_parent = link_ancestors[-1].keys
        if document is None:
            return root.delete_in(keys_to_link_parent)
        return root.set_in(keys_to_link_parent, document)

    return document