Skip to content

Instantly share code, notes, and snippets.

@laradevitt
Last active June 13, 2022 14:36
Show Gist options
  • Save laradevitt/6ab86bf7ebbd3215b20b to your computer and use it in GitHub Desktop.
Save laradevitt/6ab86bf7ebbd3215b20b to your computer and use it in GitHub Desktop.
Extends Drupal Services module to handle requests on node resource containing path alias instead of node id.
name = Services Node Alias to System Path
description = Uses the Services API to convert requests containing a node path alias to a system path (e.g., 'node/5').
core = 7.x
version = 7.x-1.0
<?php
/**
* @file
* Code for the Services Node Alias to System Path module.
*/
/**
* Implements hook_services_resources_alter().
*
* In order to handle aliases with multiple parts (e.g. about/media), the
* string in the request should have slashes converted to triple dashes (---).
*/
function services_node_alias_to_system_path_services_resources_alter(&$resources, &$endpoint) {
$args = array(
'name' => 'alias',
'optional' => FALSE,
'source' => array('path' => 0),
'type' => 'string',
'description' => 'The alias node to get',
);
$resources['node']['operations']['retrieve']['args'] = array($args);
$resources['node']['operations']['retrieve']['callback'] = '_services_node_alias_to_system_path_retrieve';
$resources['node']['operations']['retrieve']['access callback'] = '_services_node_alias_to_system_path_node_resource_access';
$resources['node']['operations']['retrieve']['access arguments append'] = TRUE;
}
function _services_node_alias_to_system_path_retrieve($alias){
$nid = _services_node_alias_to_system_path_find_nid($alias);
if ($nid) {
return _node_resource_retrieve($nid);
}
return FALSE;
}
function _services_node_alias_to_system_path_node_resource_access($op, $alias) {
$nid = _services_node_alias_to_system_path_find_nid($alias[0]);
if ($nid) {
return _node_resource_access($op, array($nid));
}
return services_error(t('Content could not be found.'), 404);
}
/**
* Helper function.
*/
function _services_node_alias_to_system_path_find_nid($alias) {
// Convert dashes to slashes.
$alias = str_replace('---', '/', $alias);
// Look up internal path.
$path = drupal_get_normal_path($alias);
// If drupal_get_normal_path() returns the alias, equate this to FALSE (no
// internal path available).
$is_node = $path !== $alias;
if ($is_node && ctype_digit($nid = str_replace('node/', '', $path))) {
return $nid;
}
return FALSE;
}
@laradevitt
Copy link
Author

@cavla Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment