Simplifying code

  • This code sample was originally from the xray_oxford_comma_list() function, but you can see when that function is covered in the section "Writing a Utility Function when Drupal APIs Miss Your Need" that this assignment has been made simpler- four lines of code instead of seven.

    $settings is passed in as a parameter.

    Original verbose code to set the default settings:

    <?php
    $default_settings
    = array(
    'comma' => ', ',
    'type' => 'and',
    'oxford' => TRUE,
    );
    $settings = array_merge($default_settings, $settings);
    extract($settings, EXTR_SKIP);
    ?>

    Cleaner, leaner replacement recommended by chx:

    <?php
    $comma
    = ', ';
    $type = 'and';
    $oxford = TRUE;
    // Overwrite default settings with any passed-in settings that apply.
    extract($settings, EXTR_IF_EXISTS);
    ?>

    ~
    This more elegant statement and overriding of Oxford comma default settings is courtesy of chx. It was made in commit d34473e9501edd140229172842c7949473351b48, which you can see on-line at http://drupalcode.org/project/xray.git/commit/d34473e or in a copy of the X-ray repository with the command git show d34473e.

    function xray_oxford_comma_list($list, $settings = array()) {
    - $default_settings = array(
    - 'comma' => ', ',
    - 'type' => 'and',
    - 'oxford' => TRUE,
    - );
    - $settings = array_merge($default_settings, $settings);
    - extract($settings, EXTR_SKIP);
    + // Set default settings.
    + $comma = ', ';
    + $type = 'and';
    + $oxford = TRUE;
    + // Overwrite default settings with any passed-in settings that apply.
    + extract($settings, EXTR_IF_EXISTS);