Final Solution
<?php
use Drupal\Core\Database\Database;
use Drupal\Component\Serialization\Yaml;
use Drupal\Component\Utility\NestedArray;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Utility\UpdateException;
/**
* Add required fields to user entities.
*/
function {module}_update_9001(){
$modulePath = \Drupal::service('extension.list.module')
->getPath('{module}');
$configPathStorageObjects = \Drupal::service('file_system')
->scanDirectory($modulePath.'/config/optional','~field\.storage\.user\..*~');
\Drupal::logger('staffdb')->notice('storage objects: <pre>'.print_r($configPathStorageObjects,true).'</pre>');
//add missing field storage
foreach ($configPathStorageObjects as $configPath){
$config = FieldStorageConfig::loadByName('user',str_replace('field.storage.user.','',$configPath->name));
if(is_null($config)){
$configSettings = Yaml::decode(
file_get_contents(
"$modulePath/config/optional/{$configPath->filename}"
)
);
$fieldStorage = FieldStorageConfig::create($configSettings);
$fieldStorage->save();
}
}
//add missing fields to users
$configPathFieldObjects = \Drupal::service('file_system')
->scanDirectory($modulePath.'/config/optional','~field\.field\.user\.user\..*~');
foreach ($configPathFieldObjects as $configPath){
$config = FieldConfig::loadByName('user', 'user', str_replace('field.field.user.user.','',$configPath->name));
if(is_null($config)){
$configSettings = Yaml::decode(
file_get_contents(
"$modulePath/config/optional/{$configPath->filename}"
)
);
$field = FieldConfig::create($configSettings);
$field->save();
}
}
}