Why am I failing to programmatically create a webform in hook_entity_insert?
The problem was at line:
'elements' =&gt; Yaml::encode($elements)

The solution is to replace the Yaml in the use statement:
from:
use Drupal\Component\Serialization\Yaml;

to:
use Symfony\Component\Yaml\Yaml;

I don't know the exact explanation, it just works on my code.