Hook block_class_update_20004 crashes at json_decode

Created on 17 March 2025, about 2 months ago

Problem/Motivation

> [notice] Update started: block_class_update_20004
> [error] json_decode(): Argument #1 ($json) must be of type string, array given
> [error] Update failed: block_class_update_20004

🐛 Bug report
Status

Active

Version

4.0

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @leontin
  • Pipeline finished with Failed
    about 2 months ago
    Total: 163s
    #450138
  • 🇦🇺Australia merlin06

    We have a similar problem but the hook is block_class_update_20017()
    We have an additional issue where we run feature:import before database updates.

    The feature:import adds additional classes in via:
    ```
    third_party_settings:
    block_class:
    classes: my-class-1
    ```

    We end up with block_classes.settings in the database that looks like:

    ```
    block_classes_stored [
    'my-class-1',
    '{my-class-2:my-class-2, my-class-3:my-class-3}',
    'my-class-4',
    ];
    ```

    This is my solution that can convert our situation into a proper array of block classes for block_class.settings.yml:
    ```
    /**
    * Convert block_classes_stored from JSON to a sequence.
    */
    function block_class_update_20017() {
    $config = \Drupal::configFactory()->getEditable('block_class.settings');

    $new_classes = [];
    $block_classes_stored = $config->get('block_classes_stored');
    foreach ($block_classes_stored as $block_classes) {
    if (is_string($block_classes)) {
    $decoded = Json::decode($block_classes);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
    // Json decoded successfully with no errors. Add it to the classes.
    $new_classes = array_merge($new_classes, $decoded);
    }
    else {
    // We have a string... but it's not a JSON encoded string. Add it to the classes.
    $new_classes[] = $block_classes;
    }
    }
    }
    $new_classes = array_unique(array_filter(array_values($new_classes)));
    $config->set('block_classes_stored', $new_classes);
    $config->save();
    }
    ```

Production build 0.71.5 2024