Skip to content

Instantly share code, notes, and snippets.

@scottpayne
Last active August 29, 2015 14:01
Show Gist options
  • Save scottpayne/ec1c7c16a4297352c82e to your computer and use it in GitHub Desktop.
Save scottpayne/ec1c7c16a4297352c82e to your computer and use it in GitHub Desktop.
<?php
/*
* This is not a full module, just a demo of how I started working with
* the Storage API Drupal module.
*
* I have working code that looks a lot like this, so it should work more
* or less. Hopefully it will be a starting point for other people to work
* with Storage API.
*/
function storage_api_spike_menu() {
$items = array();
$items['admin/config/media/storage-test'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => 'Storage API Spike',
'page callback' => 'storage_api_spike_page',
'access callback' => TRUE,
);
}
function storage_api_spike_page() {
return drupal_get_form("storage_api_spike_form");
}
function storage_api_spike_form($form, &$form_state) {
$selector = storage_selector('storage_api_spike');
$form['selector'] = $selector->formItem();
$form['actions'] = array(
'#type' => 'actions'
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function storage_api_spike_form_submit($form, $form_state) {
// update selector class
$selector = storage_selector('storage_api_spike');
$selector->submit($form_state['values']['selector']);
// create a temporary file and save it
$tempname = drupal_tempnam("temporary://", "abcde");
if ($realtemp_name = file_unmanaged_save_data("This is a file on " . date("Y-m-d H:i:s"), $tempname, FILE_EXISTS_REPLACE)) {
drupal_set_message(drupal_realpath($realtemp_name));
} else {
drupal_set_message("Couldn't write to file");
return;
}
// we use the filename as the identifier, so keep track of it
$storage_filename = 'storage_api_spike/' . drupal_basename($tempname);
// add the file to storage api
$selector->storageAdd(array(
'source_uri' => $tempname,
'filename' => $storage_filename,
));
// find the file by filename
$query = db_select('storage', 's');
$query->fields('s', array('storage_id'));
$query->addJoin('INNER', 'storage_file', 'sf', 'sf.file_id = s.file_id');
$query->condition("sf.filename", $storage_filename);
$query->condition("s.selector_id", "storage_api_spike");
$r = $query->execute();
if ($r->rowCount() != 1) {
drupal_set_message("Uh-oh! Should have found one and only one file with the name " . $storage_filename . "!", 'error');
return;
}
// load the storage
$storage_row = $r->fetchAssoc();
$storage = storage_load($storage_row['storage_id']);
// serve the file
storage_serve($storage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment