You are here

function _patterns_io_save_pattern in Patterns 7.2

Lower level primitive for patterns_io_save_pattern. Includes an optional argument to force the UUUID

Returns a patterns_results object with a message, instead of a boolean

1 call to _patterns_io_save_pattern()
patterns_io_save_pattern in includes/io/io.inc
Saves a pattern string or array into the database AND in the file system.

File

includes/io/io.inc, line 374
Functions related to input/output operations.

Code

function _patterns_io_save_pattern($content = NULL, $name = NULL, $format = PATTERNS_FORMAT_YAML, $dir = NULL, $original = NULL, $username = NULL, $uuuid = NULL) {
  $status = PATTERNS_SUCCESS;
  $msg = NULL;
  if (is_null($name)) {
    $msg = t('Cannot save pattern with \'NULL\' identifier.');
    return patterns_results(PATTERNS_ERR, $msg);
  }
  if (!patterns_validate_pattern($content, $format, PATTERNS_VALIDATE_SYNTAX)) {
    $msg = t("Pattern '%name' could not be saved. Make sure edited code is well-formed.", array(
      '%name' => $name,
    ));
    return patterns_results(PATTERNS_ERR, $msg);
  }
  if (is_null($dir)) {
    $dir = patterns_path_get_files_dir();
  }
  if (!file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
    $msg = t('Error: the pattern is not writable. Please check the file system permissions.');
    return patterns_results(PATTERNS_ERR, $msg);
  }

  // Check if the file has a valid extension
  // and in case add the format at the end
  if (!_patterns_io_file_has_valid_extension($name)) {
    $name = $name . '.' . $format;
  }
  $path_original = $dir . '/' . $name;
  if (is_null($original)) {
    if (is_array($content)) {
      $original = patterns_parser_dump($content, $format);
    }
    else {
      $original = $content;
    }
  }
  $path = file_unmanaged_save_data($original, $path_original, FILE_EXISTS_REPLACE);
  if (!$path) {
    $msg = t('An error occurred while saving the file to %path. A file with the same name exists.', array(
      '%path' => $path_original,
    ));
    return patterns_results(PATTERNS_ERR, $msg);
  }

  // Load and save pattern.
  $load_function = patterns_parser_get_parser_function($format, PATTERNS_PARSER_LOAD);
  if (!$load_function) {
    $msg = t('Could not find a parser for ', array(
      '%name' => $name,
    ));
    return patterns_results(PATTERNS_ERR, $msg);
  }
  $pattern = $load_function($path);
  if (!$pattern) {
    $msg = t("Pattern '%name' could not be saved into the database. Make sure edited code is well-formed.", array(
      '%name' => $name,
    ));
    patterns_io_remove_pattern_from_fs($path);
    return patterns_results(PATTERNS_ERR, $msg);
  }
  patterns_db_save_pattern($pattern, $path, $name, $format, $username, $uuuid);
  $link = l($name, 'admin/patterns/edit/' . $name);
  $msg = t('Pattern !name was saved in %path.', array(
    '!name' => $link,
    '%path' => $path,
  ));
  return patterns_results(PATTERNS_SUCCESS, $msg);
}