Skip to content

Instantly share code, notes, and snippets.

@whalesalad
Created February 7, 2010 13:28
Show Gist options
  • Select an option

  • Save whalesalad/297444 to your computer and use it in GitHub Desktop.

Select an option

Save whalesalad/297444 to your computer and use it in GitHub Desktop.
<?php
/*
Turn a url like 's:true:c:shoes:a:heavy' into something like
Array (
s: 'true', // safety vs. non-safety
c: 'shoes', // category = shoes
a: 'heavy // audience = heavy
);
- Split on the :, the first item will clearly be a key, whilst the second will be a value for that key.
- If the value is a-z, lowercase, and one single character, it is a key, and it's following piece (index+1) will be it's value
- We can reliably assume it will be key:value:key:value but there must be some way to ensure this 100%.
- Other possiblities, abc:value : xyz:value : x:x : x:X:X
////// methods
With being able to switch from a diff category to another
$this->set('keyword', 'value') // if exists, override, otherwise, set it
$this->get('keyword') // Get a specific keyword's value
$this->get() // no value passed, return an array of all of em
*/
class WhaleRL {
// Create a holding area for the new values
private $body;
function __construct($url) {
$url_bits = explode(':', $url);
// If the lenfth of the URL pieces is not an even number (an equal number of key:val pairs), someone failed.
if ((count($url_bits) % 2) == 1)
return false;
foreach ($url_bits as $key => $value) {
// Check to see if this is a key (one single lowercase letter)
if (preg_match("/^[a-z]$/", $value)) {
// if this returns true, this is a key, so set it in the array
$body[$value] = $url_bits[$key+1];
}
}
$this->body = $body;
// Template::debug($this->body);
}
// $this->set('keyword', 'value') // if exists, override, otherwise, set it
function set($keyword, $value = NULL) {
// $this->body[$keyword] = $value;
// return $this->body[$keyword];
return $this->body[$keyword] = $value;
}
// $this->get('keyword') // Get a specific keyword's value
function get($keyword = false) {
if ($keyword AND isset($this->body[$keyword])) {
return $this->body[$keyword];
} else if ($keyword AND !isset($this->body[$keyword])) {
return false;
} else {
return $this->body;
}
}
// Build a temporary result to use in a redirection URL. Pass an array of keywords to add or remove.
// If a keyword and a value is passed, add it or replace it, if a keyword is just sent, remove it
// Either way... the $this->body is returned.
function build($keyword, $value = false) {
$copy = $this->body;
if ($value) {
$copy[$keyword] = $value;
} else {
unset($copy[$keyword]);
}
$new_url = array();
foreach ($copy as $key => $value) {
$new_url[] = $key.':'.$value;
}
return implode(':', $new_url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment