* @license http://www.horde.org/licenses/bsd BSD
* @category Horde
* @deprecated Use Horde_Stream_Wrapper_Combine::getStream()
* @package Support
*/
class Horde_Support_CombineStream implements Horde_Stream_Wrapper_CombineStream
{
/**
* Data.
*
* @var array
*/
protected $_data;
/**
* Constructor
*
* @param array $data An array of strings and/or streams to combine into
* a single stream.
*/
public function __construct($data)
{
$this->installWrapper();
$this->_data = $data;
}
/**
* Return a stream handle to this stream.
*
* @return resource
*/
public function fopen()
{
$context = stream_context_create(array('horde-combine' => array('data' => $this)));
return fopen('horde-combine://' . spl_object_hash($this), 'rb', false, $context);
}
/**
* Return an SplFileObject representing this stream
*
* @return SplFileObject
*/
public function getFileObject()
{
$context = stream_context_create(array('horde-combine' => array('data' => $this)));
return new SplFileObject('horde-combine://' . spl_object_hash($this), 'rb', false, $context);
}
/**
* Install the horde-combine stream wrapper if it isn't already
* registered.
*
* @throws Exception
*/
public function installWrapper()
{
if (!in_array('horde-combine', stream_get_wrappers()) &&
!stream_wrapper_register('horde-combine', 'Horde_Stream_Wrapper_Combine')) {
throw new Exception('Unable to register horde-combine stream wrapper.');
}
}
/**
* Return a reference to the data.
*
* @return array
*/
public function getData()
{
return $this->_data;
}
}
Horde_Support-2.2.0/lib/Horde/Support/ConsistentHash.php 0000664 0001750 0001750 00000015116 13055004475 021354 0 ustar jan jan _numberOfReplicas = $numberOfReplicas;
$this->addNodes($nodes, $weight);
}
/**
* Get the primary node for $key.
*
* @param string $key The key to look up.
*
* @param string The primary node for $key.
*/
public function get($key)
{
$nodes = $this->getNodes($key, 1);
if (!$nodes) {
throw new Exception('No nodes found');
}
return $nodes[0];
}
/**
* Get an ordered list of nodes for $key.
*
* @param string $key The key to look up.
* @param integer $count The number of nodes to look up.
*
* @return array An ordered array of nodes.
*/
public function getNodes($key, $count = 5)
{
// Degenerate cases
if ($this->_nodeCount < $count) {
throw new Exception('Not enough nodes (have ' . $this->_nodeCount . ', ' . $count . ' requested)');
}
if ($this->_nodeCount == 0) {
return array();
}
// Simple case
if ($this->_nodeCount == 1) {
return array($this->_nodes[0]['n']);
}
$hash = $this->hash(serialize($key));
// Find the first point on the circle greater than $hash by binary search.
$low = 0;
$high = $this->_pointCount - 1;
$index = null;
while (true) {
$mid = (int)(($low + $high) / 2);
if ($mid == $this->_pointCount) {
$index = 0;
break;
}
$midval = $this->_pointMap[$mid];
$midval1 = ($mid == 0) ? 0 : $this->_pointMap[$mid - 1];
if ($midval1 < $hash && $hash <= $midval) {
$index = $mid;
break;
}
if ($midval > $hash) {
$high = $mid - 1;
} else {
$low = $mid + 1;
}
if ($low > $high) {
$index = 0;
break;
}
}
$nodes = array();
while (count($nodes) < $count) {
$nodeIndex = $this->_pointMap[$index++ % $this->_pointCount];
$nodes[$nodeIndex] = $this->_nodes[$this->_circle[$nodeIndex]]['n'];
}
return array_values($nodes);
}
/**
* Add $node with weight $weight
*
* @param mixed $node
*/
public function add($node, $weight = 1)
{
// Delegate to addNodes so that the circle is only regenerated once when
// adding multiple nodes.
$this->addNodes(array($node), $weight);
}
/**
* Add multiple nodes to the hash with the same weight.
*
* @param array $nodes An array of nodes.
* @param integer $weight The weight to add the nodes with.
*/
public function addNodes($nodes, $weight = 1)
{
foreach ($nodes as $node) {
$this->_nodes[] = array('n' => $node, 'w' => $weight);
$this->_nodeCount++;
$nodeIndex = $this->_nodeCount - 1;
$nodeString = serialize($node);
$numberOfReplicas = (int)($weight * $this->_numberOfReplicas);
for ($i = 0; $i < $numberOfReplicas; $i++) {
$this->_circle[$this->hash($nodeString . $i)] = $nodeIndex;
}
}
$this->_updateCircle();
}
/**
* Remove $node from the hash.
*
* @param mixed $node
*/
public function remove($node)
{
$nodeIndex = null;
$nodeString = serialize($node);
// Search for the node in the node list
foreach (array_keys($this->_nodes) as $i) {
if ($this->_nodes[$i]['n'] === $node) {
$nodeIndex = $i;
break;
}
}
if (is_null($nodeIndex)) {
throw new InvalidArgumentException('Node was not in the hash');
}
// Remove all points from the circle
$numberOfReplicas = (int)($this->_nodes[$nodeIndex]['w'] * $this->_numberOfReplicas);
for ($i = 0; $i < $numberOfReplicas; $i++) {
unset($this->_circle[$this->hash($nodeString . $i)]);
}
$this->_updateCircle();
// Unset the node from the node list
unset($this->_nodes[$nodeIndex]);
$this->_nodeCount--;
}
/**
* Expose the hash function for testing, probing, and extension.
*
* @param string $key
*
* @return string Hash value
*/
public function hash($key)
{
return 'h' . substr(hash('md5', $key), 0, 8);
}
/**
* Maintain the circle and arrays of points.
*/
protected function _updateCircle()
{
// Sort the circle
ksort($this->_circle);
// Now that the hashes are sorted, generate numeric indices into the
// circle.
$this->_pointMap = array_keys($this->_circle);
$this->_pointCount = count($this->_pointMap);
}
}
Horde_Support-2.2.0/lib/Horde/Support/Guid.php 0000664 0001750 0001750 00000003371 13055004475 017307 0 ustar jan jan
* $uid = (string)new Horde_Support_Guid([$opts = array()]);
*
*
* Copyright 2009-2017 Horde LLC (http://www.horde.org/)
*
* @category Horde
* @package Support
* @license http://www.horde.org/licenses/bsd
*/
class Horde_Support_Guid
{
/**
* Generated GUID.
*
* @var string
*/
private $_guid;
/**
* New GUID.
*
* @param array $opts Additional options:
*
* 'prefix' - (string) A prefix to add between the date string and the
* random string.
* DEFAULT: NONE
* 'server' - (string) The server name.
* DEFAULT: $_SERVER['SERVER_NAME'] (or 'localhost')
*
*/
public function __construct(array $opts = array())
{
$this->generate($opts);
}
/**
* Generates a GUID.
*
* @param array $opts Additional options:
*
* 'prefix' - (string) A prefix to add between the date string and the
* random string.
* DEFAULT: NONE
* 'server' - (string) The server name.
* DEFAULT: $_SERVER['SERVER_NAME'] (or 'localhost')
*
*/
public function generate(array $opts = array())
{
$this->_guid = date('YmdHis')
. '.'
. (isset($opts['prefix']) ? $opts['prefix'] . '.' : '')
. strval(new Horde_Support_Randomid())
. '@'
. (isset($opts['server']) ? $opts['server'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost'));
}
/**
* Cooerce to string.
*
* @return string
*/
public function __toString()
{
return $this->_guid;
}
}
Horde_Support-2.2.0/lib/Horde/Support/Inflector.php 0000664 0001750 0001750 00000030531 13055004475 020342 0 ustar jan jan 'moves',
'/sex$/i' => 'sexes',
'/child$/i' => 'children',
'/man$/i' => 'men',
'/foot$/i' => 'feet',
'/person$/i' => 'people',
'/(quiz)$/i' => '$1zes',
'/^(ox)$/i' => '$1en',
'/(m|l)ouse$/i' => '$1ice',
'/(matr|vert|ind)ix|ex$/i' => '$1ices',
'/(x|ch|ss|sh)$/i' => '$1es',
'/([^aeiouy]|qu)ies$/i' => '$1y',
'/([^aeiouy]|qu)y$/i' => '$1ies',
'/(?:([^f])fe|([lr])f)$/i' => '$1$2ves',
'/sis$/i' => 'ses',
'/([ti])um$/i' => '$1a',
'/(buffal|tomat)o$/i' => '$1oes',
'/(bu)s$/i' => '$1ses',
'/(alias|status)$/i' => '$1es',
'/(octop|vir)us$/i' => '$1i',
'/(ax|test)is$/i' => '$1es',
'/s$/i' => 's',
'/$/' => 's',
);
/**
* Rules for singularizing English nouns.
*
* @var array
*/
protected $_singularizationRules = array(
'/cookies$/i' => 'cookie',
'/moves$/i' => 'move',
'/sexes$/i' => 'sex',
'/children$/i' => 'child',
'/men$/i' => 'man',
'/feet$/i' => 'foot',
'/people$/i' => 'person',
'/databases$/i'=> 'database',
'/(quiz)zes$/i' => '\1',
'/(matr)ices$/i' => '\1ix',
'/(vert|ind)ices$/i' => '\1ex',
'/^(ox)en/i' => '\1',
'/(alias|status)es$/i' => '\1',
'/([octop|vir])i$/i' => '\1us',
'/(cris|ax|test)es$/i' => '\1is',
'/(shoe)s$/i' => '\1',
'/(o)es$/i' => '\1',
'/(bus)es$/i' => '\1',
'/([m|l])ice$/i' => '\1ouse',
'/(x|ch|ss|sh)es$/i' => '\1',
'/(m)ovies$/i' => '\1ovie',
'/(s)eries$/i' => '\1eries',
'/([^aeiouy]|qu)ies$/i' => '\1y',
'/([lr])ves$/i' => '\1f',
'/(tive)s$/i' => '\1',
'/(hive)s$/i' => '\1',
'/([^f])ves$/i' => '\1fe',
'/(^analy)ses$/i' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
'/([ti])a$/i' => '\1um',
'/(n)ews$/i' => '\1ews',
'/(.*)s$/i' => '\1',
);
/**
* An array of words with the same singular and plural spellings.
*
* @var array
*/
protected $_uncountables = array(
'aircraft',
'cannon',
'deer',
'equipment',
'fish',
'information',
'money',
'moose',
'rice',
'series',
'sheep',
'species',
'swine',
);
/**
* Constructor.
*
* Stores a map of the uncountable words for quicker checks.
*/
public function __construct()
{
$this->_uncountables_keys = array_flip($this->_uncountables);
}
/**
* Adds an uncountable word.
*
* @param string $word The uncountable word.
*/
public function uncountable($word)
{
$this->_uncountables[] = $word;
$this->_uncountables_keys[$word] = true;
}
/**
* Singular English word to pluralize.
*
* @param string $word Word to pluralize.
*
* @return string Plural form of $word.
*/
public function pluralize($word)
{
if ($plural = $this->getCache($word, 'pluralize')) {
return $plural;
}
if (isset($this->_uncountables_keys[$word])) {
return $word;
}
foreach ($this->_pluralizationRules as $regexp => $replacement) {
$plural = preg_replace($regexp, $replacement, $word, -1, $matches);
if ($matches > 0) {
return $this->setCache($word, 'pluralize', $plural);
}
}
return $this->setCache($word, 'pluralize', $word);
}
/**
* Plural English word to singularize.
*
* @param string $word Word to singularize.
*
* @return string Singular form of $word.
*/
public function singularize($word)
{
if ($singular = $this->getCache($word, 'singularize')) {
return $singular;
}
if (isset($this->_uncountables_keys[$word])) {
return $word;
}
foreach ($this->_singularizationRules as $regexp => $replacement) {
$singular = preg_replace($regexp, $replacement, $word, -1, $matches);
if ($matches > 0) {
return $this->setCache($word, 'singularize', $singular);
}
}
return $this->setCache($word, 'singularize', $word);
}
/**
* Camel-cases a word.
*
* @todo Do we want locale-specific or locale-independent camel casing?
*
* @param string $word The word to camel-case.
* @param string $firstLetter Whether to upper or lower case the first.
* letter of each slash-separated section.
*
* @return string Camelized $word
*/
public function camelize($word, $firstLetter = 'upper')
{
if ($camelized = $this->getCache($word, 'camelize' . $firstLetter)) {
return $camelized;
}
$camelized = $word;
if (Horde_String::lower($camelized) != $camelized &&
strpos($camelized, '_') !== false) {
$camelized = str_replace('_', '/', $camelized);
}
if (strpos($camelized, '/') !== false) {
$camelized = str_replace('/', '/ ', $camelized);
}
if (strpos($camelized, '_') !== false) {
$camelized = strtr($camelized, '_', ' ');
}
$camelized = str_replace(' ', '', Horde_String::ucwords($camelized));
if ($firstLetter == 'lower') {
$parts = array();
foreach (explode('/', $camelized) as $part) {
$part[0] = Horde_String::lower($part[0]);
$parts[] = $part;
}
$camelized = implode('/', $parts);
}
return $this->setCache($word, 'camelize' . $firstLetter, $camelized);
}
/**
* Capitalizes all the words and replaces some characters in the string to
* create a nicer looking title.
*
* Titleize is meant for creating pretty output.
*
* See:
* - http://daringfireball.net/2008/05/title_case
* - http://daringfireball.net/2008/08/title_case_update
*
* Examples:
* 1. titleize("man from the boondocks") => "Man From The Boondocks"
* 2. titleize("x-men: the last stand") => "X Men: The Last Stand"
*/
public function titleize($word)
{
throw new Exception('not implemented yet');
}
/**
* The reverse of camelize().
*
* Makes an underscored form from the expression in the string.
*
* Examples:
* 1. underscore("ActiveRecord") => "active_record"
* 2. underscore("ActiveRecord_Errors") => "active_record_errors"
*
* @todo Do we want locale-specific or locale-independent lowercasing?
*/
public function underscore($camelCasedWord)
{
$word = $camelCasedWord;
if ($result = $this->getCache($word, 'underscore')) {
return $result;
}
$result = Horde_String::lower(preg_replace('/([a-z])([A-Z])/', "\${1}_\${2}", $word));
return $this->setCache($word, 'underscore', $result);
}
/**
* Replaces underscores with dashes in the string.
*
* Example:
* 1. dasherize("puni_puni") => "puni-puni"
*/
public function dasherize($underscoredWord)
{
if ($result = $this->getCache($underscoredWord, 'dasherize')) {
return $result;
}
$result = str_replace('_', '-', $this->underscore($underscoredWord));
return $this->setCache($underscoredWord, 'dasherize', $result);
}
/**
* Capitalizes the first word and turns underscores into spaces and strips
* _id.
*
* Like titleize(), this is meant for creating pretty output.
*
* Examples:
* 1. humanize("employee_salary") => "Employee salary"
* 2. humanize("author_id") => "Author"
*/
public function humanize($lowerCaseAndUnderscoredWord)
{
$word = $lowerCaseAndUnderscoredWord;
if ($result = $this->getCache($word, 'humanize')) {
return $result;
}
$result = ucfirst(str_replace('_', ' ', $this->underscore($word)));
if (substr($result, -3, 3) == ' id') {
$result = str_replace(' id', '', $result);
}
return $this->setCache($word, 'humanize', $result);
}
/**
* Removes the module part from the expression in the string.
*
* Examples:
* 1. demodulize("Fax_Job") => "Job"
* 1. demodulize("User") => "User"
*/
public function demodulize($classNameInModule)
{
$result = explode('_', $classNameInModule);
return array_pop($result);
}
/**
* Creates the name of a table like Rails does for models to table names.
*
* This method uses the pluralize() method on the last word in the string.
*
* Examples:
* 1. tableize("RawScaledScorer") => "raw_scaled_scorers"
* 2. tableize("egg_and_ham") => "egg_and_hams"
* 3. tableize("fancyCategory") => "fancy_categories"
*/
public function tableize($className)
{
if ($result = $this->getCache($className, 'tableize')) {
return $result;
}
$result = $this->pluralize($this->underscore($className));
$result = str_replace('/', '_', $result);
return $this->setCache($className, 'tableize', $result);
}
/**
* Creates a class name from a table name like Rails does for table names
* to models.
*
* Examples:
* 1. classify("egg_and_hams") => "EggAndHam"
* 2. classify("post") => "Post"
*/
public function classify($tableName)
{
if ($result = $this->getCache($tableName, 'classify')) {
return $result;
}
$result = $this->camelize($this->singularize($tableName));
// classes use underscores instead of slashes for namespaces
$result = str_replace('/', '_', $result);
return $this->setCache($tableName, 'classify', $result);
}
/**
* Creates a foreign key name from a class name.
*
* $separateClassNameAndIdWithUnderscore sets whether the method should put
* '_' between the name and 'id'.
*
* Examples:
* 1. foreignKey("Message") => "message_id"
* 2. foreignKey("Message", false) => "messageid"
* 3. foreignKey("Fax_Job") => "fax_job_id"
*/
public function foreignKey($className, $separateClassNameAndIdWithUnderscore = true)
{
throw new Exception('not implemented yet');
}
/**
* Turns a number into an ordinal string used to denote the position in an
* ordered sequence such as 1st, 2nd, 3rd, 4th.
*
* Examples:
* 1. ordinalize(1) => "1st"
* 2. ordinalize(2) => "2nd"
* 3. ordinalize(1002) => "1002nd"
* 4. ordinalize(1003) => "1003rd"
*/
public function ordinalize($number)
{
throw new Exception('not implemented yet');
}
/**
* Clears the inflection cache.
*/
public function clearCache()
{
$this->_cache = array();
}
/**
* Retuns a cached inflection.
*
* @return string | false
*/
public function getCache($word, $rule)
{
return isset($this->_cache[$word . '|' . $rule]) ?
$this->_cache[$word . '|' . $rule] : false;
}
/**
* Caches an inflection.
*
* @param string $word The word being inflected.
* @param string $rule The inflection rule.
* @param string $value The inflected value of $word.
*
* @return string The inflected value
*/
public function setCache($word, $rule, $value)
{
$this->_cache[$word . '|' . $rule] = $value;
return $value;
}
}
Horde_Support-2.2.0/lib/Horde/Support/Memory.php 0000664 0001750 0001750 00000005222 13055004475 017664 0 ustar jan jan
* $t = new Horde_Support_Memory;
* $t->push();
* $used = $t->pop();
*
*
* Do not expect too much of this memory tracker. Profiling memory is not
* trivial as your placement of the measurements may obscure important
* information. As a trivial example: Assuming that your script used 20 MB of
* memory befory you call push() the information you get when calling pop()
* might only tell you that there was less than 20 MB of memory consumed in
* between the two calls. Take the changes to internal memory handling of PHP in
* between the different versions into account
* (http://de3.php.net/manual/en/features.gc.performance-considerations.php) and
* you should get an idea about why you might be cautious about the values you
* get from this memory tracker.
*
* Copyright 2011-2017 Horde LLC (http://www.horde.org/)
*
* @category Horde
* @package Support
* @license http://www.horde.org/licenses/bsd
*/
class Horde_Support_Memory
{
/**
* Holds the starting memory consumption.
*
* @var array
*/
protected $_start = array();
/**
* Current index for stacked trackers.
*
* @var integer
*/
protected $_idx = 0;
/**
* Push a new tracker on the stack.
*/
public function push()
{
$start = $this->_start[$this->_idx++] = array(
memory_get_usage(),
memory_get_peak_usage(),
memory_get_usage(true),
memory_get_peak_usage(true)
);
return $start;
}
/**
* Pop the latest tracker and return the difference with the current
* memory situation.
*
* @return array The change in memory allocated via emalloc() in between the
* push() and the pop() call. The array holds four values: the
* first one indicates the change in current usage of memory
* while the second value indicates any changes in the peak
* amount of memory used. The third and fourth value show
* current and peak usage as well but indicate the real memory
* usage and not just the part allocated via emalloc(),
*/
public function pop()
{
if (! ($this->_idx > 0)) {
throw new Exception('No timers have been started');
}
$start = $this->_start[--$this->_idx];
return array(
memory_get_usage() - $start[0],
memory_get_peak_usage() - $start[1],
memory_get_usage(true) - $start[2],
memory_get_peak_usage(true) - $start[3]
);
}
}
Horde_Support-2.2.0/lib/Horde/Support/Numerizer.php 0000664 0001750 0001750 00000002527 13055004475 020401 0 ustar jan jan
* @license http://www.horde.org/licenses/bsd BSD
* @category Horde
* @package Support
*/
/**
* @author Chuck Hagenbuch
* @license http://www.horde.org/licenses/bsd BSD
* @category Horde
* @package Support
*/
class Horde_Support_Numerizer
{
public static function numerize($string, $args = array())
{
return self::factory($args)->numerize($string);
}
public static function factory($args = array())
{
$locale = isset($args['locale']) ? $args['locale'] : null;
if ($locale && Horde_String::lower($locale) != 'base') {
$locale = str_replace(' ', '_', Horde_String::ucwords(str_replace('_', ' ', Horde_String::lower($locale))));
$class = 'Horde_Support_Numerizer_Locale_' . $locale;
if (class_exists($class)) {
return new $class($args);
}
list($language,) = explode('_', $locale);
if ($language != $locale) {
$class = 'Horde_Support_Numerizer_Locale_' . $language;
if (class_exists($class)) {
return new $class($args);
}
}
}
return new Horde_Support_Numerizer_Locale_Base($args);
}
}
Horde_Support-2.2.0/lib/Horde/Support/ObjectStub.php 0000664 0001750 0001750 00000002356 13055004475 020465 0 ustar jan jan
* @category Horde
* @license http://www.horde.org/licenses/bsd BSD
* @package Support
*/
/**
* @author Michael Slusarz
* @category Horde
* @license http://www.horde.org/licenses/bsd BSD
* @package Support
*/
class Horde_Support_ObjectStub
{
/**
* Original data object.
*
* @var array
*/
protected $_data;
/**
* Constructor
*
* @param object $data The original data object.
*/
public function __construct($data)
{
$this->_data = $data;
}
/**
*/
public function __get($name)
{
return isset($this->_data->$name)
? $this->_data->$name
: null;
}
/**
*/
public function __set($name, $value)
{
$this->_data->$name = $value;
}
/**
*/
public function __isset($name)
{
return isset($this->_data->$name);
}
/**
*/
public function __unset($name)
{
unset($this->_data->$name);
}
}
Horde_Support-2.2.0/lib/Horde/Support/Randomid.php 0000664 0001750 0001750 00000003322 13055004475 020150 0 ustar jan jan
* $id = (string)new Horde_Support_Randomid();
*
*
* Copyright 2010-2017 Horde LLC (http://www.horde.org/)
*
* @author Michael Slusarz
* @category Horde
* @license http://www.horde.org/licenses/bsd BSD
* @package Support
*/
class Horde_Support_Randomid
{
/**
* Generated ID.
*
* @var string
*/
private $_id;
/**
* New random ID.
*/
public function __construct()
{
$this->_id = $this->generate();
}
/**
* Generate a random ID.
*/
public function generate()
{
$elts = array(
uniqid(),
mt_rand(),
getmypid(),
spl_object_hash($this)
);
if (function_exists('zend_thread_id')) {
$elts[] = zend_thread_id();
}
if (function_exists('sys_getloadavg') &&
($loadavg = sys_getloadavg())) {
$elts = array_merge($elts, $loadavg);
}
if (function_exists('memory_get_usage')) {
$elts[] = memory_get_usage();
$elts[] = memory_get_peak_usage();
}
shuffle($elts);
/* Base64 can have /, +, and = characters. Restrict to URL-safe
* characters. */
return substr(str_replace(
array('/', '+', '='),
array('-', '_', ''),
base64_encode(hash('sha1', serialize($elts), true))
), 0, 23);
}
/**
* Cooerce to string.
*
* @return string The random ID.
*/
public function __toString()
{
return $this->_id;
}
}
Horde_Support-2.2.0/lib/Horde/Support/Stack.php 0000664 0001750 0001750 00000001446 13055004475 017465 0 ustar jan jan _stack = $stack;
}
public function push($value)
{
$this->_stack[] = $value;
}
public function pop()
{
return array_pop($this->_stack);
}
public function peek($offset = 1)
{
if (isset($this->_stack[count($this->_stack) - $offset])) {
return $this->_stack[count($this->_stack) - $offset];
} else {
return null;
}
}
}
Horde_Support-2.2.0/lib/Horde/Support/StringStream.php 0000664 0001750 0001750 00000004371 13055004475 021042 0 ustar jan jan
* @category Horde
* @license http://www.horde.org/licenses/bsd BSD
* @package Support
*/
/**
* @author Chuck Hagenbuch
* @category Horde
* @deprecated Use Horde_Stream_Wrapper_String::getStream()
* @license http://www.horde.org/licenses/bsd BSD
* @package Support
*/
class Horde_Support_StringStream implements Horde_Stream_Wrapper_StringStream
{
/* Wrapper name. */
const WNAME = 'horde-string';
/**
* String data.
*
* @var string
*/
protected $_string;
/**
* Constructor
*
* @param string &$string Reference to the string to wrap as a stream
*/
public function __construct(&$string)
{
$this->installWrapper();
$this->_string =& $string;
}
/**
* Return a stream handle to this string stream.
*
* @return resource
*/
public function fopen()
{
return fopen(
self::WNAME . '://' . spl_object_hash($this),
'rb',
false,
stream_context_create(array(
self::WNAME => array(
'string' => $this
)
))
);
}
/**
* Return an SplFileObject representing this string stream
*
* @return SplFileObject
*/
public function getFileObject()
{
return new SplFileObject(
self::WNAME . '://' . spl_object_hash($this),
'rb',
false,
stream_context_create(array(
self::WNAME => array(
'string' => $this
)
))
);
}
/**
* Install the stream wrapper if it isn't already registered.
*/
public function installWrapper()
{
if (!in_array(self::WNAME, stream_get_wrappers()) &&
!stream_wrapper_register(self::WNAME, 'Horde_Stream_Wrapper_String')) {
throw new Exception('Unable to register stream wrapper.');
}
}
/**
* Return a reference to the wrapped string.
*
* @return string
*/
public function &getString()
{
return $this->_string;
}
}
Horde_Support-2.2.0/lib/Horde/Support/Stub.php 0000664 0001750 0001750 00000005027 13055004475 017334 0 ustar jan jan
* $t = new Horde_Support_Timer;
* $t->push();
* $elapsed = $t->pop();
*
*
* Copyright 1999-2017 Horde LLC (http://www.horde.org/)
*
* @category Horde
* @package Support
* @license http://www.horde.org/licenses/bsd
*/
class Horde_Support_Timer
{
/**
* Holds the starting timestamp.
*
* @var array
*/
protected $_start = array();
/**
* Current index for stacked timers.
*
* @var integer
*/
protected $_idx = 0;
/**
* Push a new timer start on the stack.
*/
public function push()
{
$start = $this->_start[$this->_idx++] = microtime(true);
return $start;
}
/**
* Pop the latest timer start and return the difference with the current
* time.
*
* @return float The amount of time passed.
*/
public function pop()
{
$etime = microtime(true);
if (! ($this->_idx > 0)) {
throw new Exception('No timers have been started');
}
return $etime - $this->_start[--$this->_idx];
}
}
Horde_Support-2.2.0/lib/Horde/Support/Uuid.php 0000664 0001750 0001750 00000004443 13055004475 017326 0 ustar jan jan
* $uuid = (string)new Horde_Support_Uuid;
*
*
* Copyright 2008-2017 Horde LLC (http://www.horde.org/)
*
* @category Horde
* @package Support
* @license http://www.horde.org/licenses/bsd
*/
class Horde_Support_Uuid
{
/**
* Generated UUID
* @var string
*/
private $_uuid;
/**
* New UUID.
*/
public function __construct()
{
$this->generate();
}
/**
* Generate a 36-character RFC 4122 UUID, without the urn:uuid: prefix.
*
* @see http://www.ietf.org/rfc/rfc4122.txt
* @see http://labs.omniti.com/alexandria/trunk/OmniTI/Util/UUID.php
*/
public function generate()
{
$this->_uuid = null;
if (extension_loaded('uuid')) {
if (function_exists('uuid_export')) {
// UUID extension from http://www.ossp.org/pkg/lib/uuid/
if (uuid_create($ctx) == UUID_RC_OK &&
uuid_make($ctx, UUID_MAKE_V4) == UUID_RC_OK &&
uuid_export($ctx, UUID_FMT_STR, $str) == UUID_RC_OK) {
$this->_uuid = $str;
uuid_destroy($ctx);
}
} else {
// UUID extension from http://pecl.php.net/package/uuid
$this->_uuid = uuid_create();
}
}
if (!$this->_uuid) {
list($time_mid, $time_low) = explode(' ', microtime());
$time_low = (int)$time_low;
$time_mid = (int)substr($time_mid, 2) & 0xffff;
$time_high = mt_rand(0, 0x0fff) | 0x4000;
$clock = mt_rand(0, 0x3fff) | 0x8000;
$node_low = function_exists('zend_thread_id')
? zend_thread_id()
: getmypid();
$node_high = isset($_SERVER['SERVER_ADDR'])
? ip2long($_SERVER['SERVER_ADDR'])
: crc32(php_uname());
$node = bin2hex(pack('nN', $node_low, $node_high));
$this->_uuid = sprintf('%08x-%04x-%04x-%04x-%s',
$time_low, $time_mid, $time_high, $clock, $node);
}
}
/**
* Cooerce to string.
*
* @return string UUID.
*/
public function __toString()
{
return $this->_uuid;
}
}
Horde_Support-2.2.0/test/Horde/Support/Numerizer/Locale/BaseTest.php 0000664 0001750 0001750 00000005066 13055004475 023524 0 ustar jan jan 'one',
5 => 'five',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
27 => 'twenty seven',
31 => 'thirty-one',
59 => 'fifty nine',
100 => 'a hundred',
100 => 'one hundred',
150 => 'one hundred and fifty',
// 150 => 'one fifty',
200 => 'two-hundred',
500 => '5 hundred',
999 => 'nine hundred and ninety nine',
1000 => 'one thousand',
1200 => 'twelve hundred',
1200 => 'one thousand two hundred',
17000 => 'seventeen thousand',
21473 => 'twentyone-thousand-four-hundred-and-seventy-three',
74002 => 'seventy four thousand and two',
99999 => 'ninety nine thousand nine hundred ninety nine',
100000 => '100 thousand',
250000 => 'two hundred fifty thousand',
1000000 => 'one million',
1250007 => 'one million two hundred fifty thousand and seven',
1000000000 => 'one billion',
1000000001 => 'one billion and one',
);
foreach ($strings as $key => $string) {
$this->assertEquals($key, (int)$numerizer->numerize($string));
}
}
public function testMissspelledForty()
{
$numerizer = Horde_Support_Numerizer::factory();
$this->assertEquals(40, $numerizer->numerize('forty'));
$this->assertEquals(40, $numerizer->numerize('fourty'));
}
public function testLeavesDatesAlone()
{
$numerizer = Horde_Support_Numerizer::factory();
$this->assertEquals('2006-08-20 03:00', $numerizer->numerize('2006-08-20 03:00'));
$this->assertEquals('2006-08-20 15:30:30', $numerizer->numerize('2006-08-20 15:30:30'));
}
public function testStaticNumerize()
{
$this->assertEquals('2006-08-20 03:00', Horde_Support_Numerizer::numerize('2006-08-20 03:00'));
}
}
Horde_Support-2.2.0/test/Horde/Support/Numerizer/Locale/DeTest.php 0000664 0001750 0001750 00000005303 13055004475 023174 0 ustar jan jan 'de'));
$strings = array(
array(1, 'eins'),
array(5, 'fünf'),
array(10, 'zehn'),
array(11, 'elf'),
array(12, 'zwölf'),
array(13, 'dreizehn'),
array(14, 'vierzehn'),
array(15, 'fünfzehn'),
array(16, 'sechzehn'),
array(17, 'siebzehn'),
array(18, 'achtzehn'),
array(19, 'neunzehn'),
array(20, 'zwanzig'),
array(27, 'siebenundzwanzig'),
array(31, 'einunddreißig'),
array(59, 'neunundfünfzig'),
array(100, 'einhundert'),
array(100, 'ein hundert'),
array(150, 'hundertundfünfzig'),
array(150, 'einhundertundfünfzig'),
array(200, 'zweihundert'),
array(500, 'fünfhundert'),
array(999, 'neunhundertneunundneunzig'),
array(1000, 'eintausend'),
array(1200, 'zwölfhundert'),
array(1200, 'eintausendzweihundert'),
array(17000, 'siebzehntausend'),
array(21473, 'einundzwanzigtausendvierhundertdreiundsiebzig'),
array(74002, 'vierundsiebzigtausendzwei'),
array(74002, 'vierundsiebzigtausendundzwei'),
array(99999, 'neunundneunzigtausendneunhundertneunundneunzig'),
array(100000, 'hunderttausend'),
array(100000, 'einhunderttausend'),
array(250000, 'zweihundertfünfzigtausend'),
array(1000000, 'eine million'),
array(1250007, 'eine million zweihundertfünfzigtausendundsieben'),
array(1000000000, 'eine milliarde'),
array(1000000001, 'eine milliarde und eins'),
);
foreach ($strings as $pair) {
$this->assertEquals((string)$pair[0], $numerizer->numerize($pair[1]));
}
}
public function testLocaleVariants()
{
$this->assertInstanceOf('Horde_Support_Numerizer_Locale_De', Horde_Support_Numerizer::factory(array('locale' => 'de_DE')));
$this->assertInstanceOf('Horde_Support_Numerizer_Locale_De', Horde_Support_Numerizer::factory(array('locale' => 'de_at')));
}
public function testStaticNumerize()
{
$this->assertEquals(1250007, Horde_Support_Numerizer::numerize('eine million zweihundertfünfzigtausendundsieben', array('locale' => 'de')));
}
}
Horde_Support-2.2.0/test/Horde/Support/AllTests.php 0000664 0001750 0001750 00000000132 13055004475 020353 0 ustar jan jan run();
Horde_Support-2.2.0/test/Horde/Support/ArrayTest.php 0000664 0001750 0001750 00000013470 13055004475 020547 0 ustar jan jan assertInstanceOf('ArrayAccess', $o);
}
public function testImplementsTraversable()
{
$o = new Horde_Support_Array();
$this->assertInstanceOf('Traversable', $o);
}
public function testImplementsCountable()
{
$o = new Horde_Support_Array();
$this->assertInstanceOf('Countable', $o);
}
// offsetGet()
public function testOffsetGetReturnsValueAtOffset()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$this->assertEquals('bar', $o->offsetGet('foo'));
}
public function testOffsetGetReturnsNullWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertNull($o->offsetGet('foo'));
}
// get()
public function testGetReturnsValueAtOffset()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$this->assertEquals('bar', $o->get('foo'));
}
public function testGetReturnsNullByDefaultWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertNull($o->get('foo'));
}
public function testGetReturnsDefaultSpecifiedWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertEquals('bar', $o->get('foo', 'bar'));
}
public function testGetReturnsDefaultSpecifiedWhenValueAtOffsetIsNull()
{
$o = new Horde_Support_Array(array('foo' => null));
$this->assertEquals('bar', $o->get('foo', 'bar'));
}
// getOrSet()
public function testGetOrSetReturnsValueAtOffset()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$this->assertEquals('bar', $o->getOrSet('foo'));
}
public function testGetOrSetReturnsAndSetsNullWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertNull($o->getOrSet('foo'));
$this->assertTrue($o->offsetExists('foo'));
$this->assertNull($o->offsetGet('foo'));
}
public function testGetOrSetReturnsAndSetsDefaultSpecifiedWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertEquals('bar', $o->getOrSet('foo', 'bar'));
$this->assertTrue($o->offsetExists('foo'));
$this->assertEquals('bar', $o->offsetGet('foo'));
}
public function testGetOrSetReturnsAndSetsDefaultSpecifiedValueAtOffsetIsNull()
{
$o = new Horde_Support_Array(array('foo' => null));
$this->assertEquals('bar', $o->getOrSet('foo', 'bar'));
$this->assertTrue($o->offsetExists('foo'));
$this->assertEquals('bar', $o->offsetGet('foo'));
}
// pop()
public function testPopReturnsValueAtOffsetAndUnsetsIt()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$this->assertEquals('bar', $o->pop('foo'));
$this->assertFalse($o->offsetExists('foo'));
}
public function testPopReturnsNullByDefaultWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertNull($o->pop('foo'));
}
public function testPopReturnsDefaultSpecifiedWhenOffsetDoesNotExist()
{
$o = new Horde_Support_Array();
$this->assertEquals('bar', $o->pop('foo', 'bar'));
}
public function testPopReturnsDefaultSpecifiedWhenValueAtOffsetIsNull()
{
$o = new Horde_Support_Array(array('foo' => null));
$this->assertEquals('bar', $o->pop('foo', 'bar'));
}
// update()
public function testUpdateDoesNotThrowWhenArgumentIsAnArray()
{
$o = new Horde_Support_Array();
$o->update(array());
}
public function testUpdateDoesNotThrowWhenArgumentIsTraversable()
{
$o = new Horde_Support_Array();
$o->update(new ArrayObject());
}
public function testUpdateMergesNewValuesFromArayInArgument()
{
$o = new Horde_Support_Array();
$o->update(array('foo' => 'bar'));
$this->assertEquals('bar', $o->offsetGet('foo'));
}
public function testUpdateMergesAndOverwritesExistingOffsets()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$o->update(array('foo' => 'baz'));
$this->assertEquals('baz', $o->offsetGet('foo'));
}
public function testUpdateMergeDoesNotAffectUnrelatedKeys()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$o->update(array('baz' => 'qux'));
$this->assertEquals('qux', $o->offsetGet('baz'));
}
// clear()
public function testClearErasesTheArray()
{
$o = new Horde_Support_Array(array('foo' => 'bar'));
$o->clear();
$this->assertEquals(0, $o->count());
}
// getKeys()
public function testGetKeysReturnsEmptyArrayWhenArrayIsEmpty()
{
$o = new Horde_Support_Array();
$this->assertSame(array(), $o->getKeys());
}
public function testGetKeysReturnsArrayOfKeysInTheArray()
{
$o = new Horde_Support_Array(array('foo'=> 1, 'bar' => 2));
$this->assertSame(array('foo', 'bar'), $o->getKeys());
}
// getValues()
public function testGetValuesReturnsEmptyArrayWhenArrayIsEmpty()
{
$o = new Horde_Support_Array();
$this->assertSame(array(), $o->getValues());
}
public function testGetValuesReturnsArrayOfValuesInTheArray()
{
$o = new Horde_Support_Array(array('foo' => 1, 'bar' => 2));
$this->assertSame(array(1, 2), $o->getValues());
}
}
Horde_Support-2.2.0/test/Horde/Support/BacktraceTest.php 0000664 0001750 0001750 00000005575 13055004475 021357 0 ustar jan jan getCurrentContext();
$this->assertEquals(__FUNCTION__, $caller['function']);
}
public function testCreateFromGeneratedBacktrace()
{
$trace = new Horde_Support_Backtrace($this->returnBacktrace());
$caller = $trace->getCurrentContext();
$this->assertEquals('returnBacktrace', $caller['function']);
$caller = $trace->getCallingContext();
$this->assertEquals(__FUNCTION__, $caller['function']);
}
public function testCreateFromException()
{
try {
$this->generateUncaughtException();
} catch (Exception $e) {
}
$trace = new Horde_Support_Backtrace($e);
$caller = $trace->getCurrentContext();
$this->assertEquals('generateUncaughtException', $caller['function']);
$caller = $trace->getCallingContext();
$this->assertEquals(__FUNCTION__, $caller['function']);
}
public function testNestingLevelOfDefaultVsGeneratedBacktrace()
{
$t1 = new Horde_Support_Backtrace();
$t2 = new Horde_Support_Backtrace($this->returnBacktrace());
$this->assertEquals($t1->getCurrentContext(), $t2->getCallingContext());
}
public function testNestingLevel()
{
$backtrace = new Horde_Support_Backtrace();
$dbt = debug_backtrace();
$this->assertEquals(count($dbt), $backtrace->getNestingLevel());
}
public function testToString()
{
$backtrace = new Horde_Support_Backtrace(array_slice($this->instanceMethod(), 0, 4));
$file = __FILE__;
$this->assertEquals("1. Horde_Support_BacktraceTest->testToString()
2. Horde_Support_BacktraceTest->instanceMethod() $file:88
3. Horde_Support_BacktraceTest::staticMethod() $file:28
4. backtraceTestFunction() $file:33
",
(string)$backtrace);
}
public function returnBacktrace()
{
return debug_backtrace();
}
public function generateUncaughtException()
{
throw new Exception();
}
}
Horde_Support-2.2.0/test/Horde/Support/bootstrap.php 0000664 0001750 0001750 00000000143 13055004475 020637 0 ustar jan jan assertInstanceOf($interface, $o);
}
public function implementsProvider()
{
return array(
array('ArrayAccess'),
array('Traversable'),
array('Countable')
);
}
public function testOffsetGetReturnsValueAtOffset()
{
$o = new Horde_Support_CaseInsensitiveArray(array('foo' => 'bar'));
$this->assertEquals('bar', $o['foo']);
}
public function testOffsetGetReturnsNullWhenOffsetDoesNotExist()
{
$o = new Horde_Support_CaseInsensitiveArray();
$this->assertNull($o['foo']);
}
public function testCaseInsensitiveKeys()
{
$o = new Horde_Support_CaseInsensitiveArray(array('foo' => 'bar'));
$this->assertTrue(isset($o['foo']));
$this->assertTrue(isset($o['Foo']));
$this->assertTrue(isset($o['FOO']));
$this->assertEquals(
'bar',
$o['foo']
);
$this->assertEquals(
'bar',
$o['Foo']
);
$this->assertEquals(
'bar',
$o['FOO']
);
unset($o['FOO']);
$this->assertFalse(isset($o['foo']));
}
}
Horde_Support-2.2.0/test/Horde/Support/CombineStreamTest.php 0000664 0001750 0001750 00000002374 13055004475 022222 0 ustar jan jan fopen();
$this->assertEquals('ABCDE12345fghij', fread($stream, 1024));
$this->assertEquals(true, feof($stream));
$this->assertEquals(0, fseek($stream, 0));
$this->assertEquals(-1, fseek($stream, 0));
$this->assertEquals(0, ftell($stream));
$this->assertEquals(0, fseek($stream, 5, SEEK_CUR));
$this->assertEquals(5, ftell($stream));
$this->assertEquals(10, fwrite($stream, '0000000000'));
$this->assertEquals(0, fseek($stream, 0, SEEK_END));
$this->assertEquals(20, ftell($stream));
$this->assertEquals(false, feof($stream));
fclose($stream);
}
}
Horde_Support-2.2.0/test/Horde/Support/ConsistentHashTest.php 0000664 0001750 0001750 00000017445 13055004475 022434 0 ustar jan jan assertEquals(0, $this->readAttribute($h, '_nodeCount'));
$h->add('a');
$this->assertEquals(1, $this->readAttribute($h, '_nodeCount'));
$this->assertEquals(count($this->readAttribute($h, '_nodes')), $this->readAttribute($h, '_nodeCount'));
}
public function testAddUpdatesPointCount()
{
$numberOfReplicas = 100;
$h = new Horde_Support_ConsistentHash(array(), 1, $numberOfReplicas);
$this->assertEquals(0, $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_circle')), $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_pointMap')), $this->readAttribute($h, '_pointCount'));
$h->add('a');
$this->assertEquals(100, $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_circle')), $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_pointMap')), $this->readAttribute($h, '_pointCount'));
}
public function testAddWithWeightGeneratesMorePoints()
{
$weight = 2;
$numberOfReplicas = 100;
$h = new Horde_Support_ConsistentHash(array(), 1, $numberOfReplicas);
$this->assertEquals(0, $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_circle')), $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_pointMap')), $this->readAttribute($h, '_pointCount'));
$h->add('a', $weight);
$this->assertEquals($numberOfReplicas * $weight, $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_circle')), $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_pointMap')), $this->readAttribute($h, '_pointCount'));
}
public function testRemoveRemovesPoints()
{
$h = new Horde_Support_ConsistentHash;
$this->assertEquals(0, $this->readAttribute($h, '_nodeCount'));
$h->add('a');
$h->remove('a');
$this->assertEquals(0, $this->readAttribute($h, '_nodeCount'));
$this->assertEquals(0, $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_circle')), $this->readAttribute($h, '_pointCount'));
$this->assertEquals(count($this->readAttribute($h, '_pointMap')), $this->readAttribute($h, '_pointCount'));
}
public function testRemoveThrowsOnNonexistentNode()
{
$h = new Horde_Support_ConsistentHash;
$this->setExpectedException('InvalidArgumentException');
$h->remove('a');
}
public function testLookupsReturnValidNodes()
{
$nodes = range(1, 10);
$h = new Horde_Support_ConsistentHash($nodes);
foreach (range(1, 10) as $i) {
$this->assertContains($h->get($i), $nodes);
}
}
public function testLookupRatiosWithDifferentNodeWeights()
{
$h = new Horde_Support_ConsistentHash;
$h->add('a', 2);
$h->add('b', 1);
$h->add('c', 3);
$h->add('d', 4);
$choices = array('a' => 0, 'b' => 0, 'c' => 0, 'd' => 0);
for ($i = 0; $i < 1000; $i++) {
$choices[$h->get(uniqid(mt_rand()))]++;
}
// Due to randomness it's entirely possible to have some overlap in the
// middle, but the highest-weighted node should definitely be chosen
// more than the lowest-weighted one.
$this->assertGreaterThan($choices['b'], $choices['d']);
}
public function testRepeatableLookups()
{
$h = new Horde_Support_ConsistentHash(range(1, 10));
$this->assertEquals($h->get('t1'), $h->get('t1'));
$this->assertEquals($h->get('t2'), $h->get('t2'));
}
public function testRepeatableLookupsAfterAddingAndRemoving()
{
$h = new Horde_Support_ConsistentHash(range(1, 100));
$results1 = array();
foreach (range(1, 100) as $i)
$results1[] = $h->get($i);
$h->add('new');
$h->remove('new');
$h->add('new');
$h->remove('new');
$results2 = array();
foreach (range(1, 100) as $i)
$results2[] = $h->get($i);
$this->assertEquals($results1, $results2);
}
public function testRepeatableLookupsBetweenInstances()
{
$h1 = new Horde_Support_ConsistentHash(range(1, 10));
$results1 = array();
foreach (range(1, 100) as $i)
$results1[] = $h1->get($i);
$h2 = new Horde_Support_ConsistentHash(range(1, 10));
$results2 = array();
foreach (range(1, 100) as $i)
$results2[] = $h2->get($i);
$this->assertEquals($results1, $results2);
}
public function testGetNodes()
{
$h = new Horde_Support_ConsistentHash(range(1, 10));
$nodes = $h->getNodes('r', 2);
$this->assertInternalType('array', $nodes);
$this->assertEquals(count($nodes), 2);
$this->assertNotEquals($nodes[0], $nodes[1]);
}
public function testGetNodesWithNotEnoughNodes()
{
$h = new Horde_Support_ConsistentHash(array('t'));
try {
$h->getNodes('resource', 2);
$this->fail('Expected Exception');
} catch (Exception $e) {}
}
public function testGetNodesWrapsToBeginningOfCircle()
{
$h = new Horde_Support_ConsistentHash(array(), 1, 1);
// Create an array of random values and one fixed test value and sort
// them by their hashes
$nodes = array();
for ($i = 0; $i < 10; $i++) {
$val = uniqid(mt_rand(), true);
$nodes[$h->hash(serialize($val) . '0')] = $val;
}
$nodes[$h->hash(serialize('key'))] = 'key';
ksort($nodes);
// Remove the fixed test value.
$nodes = array_values($nodes);
$testindex = array_search('key', $nodes);
array_splice($nodes, $testindex, 1);
foreach ($nodes as $node) {
$h->add($node);
}
$expected = array();
for ($i = 0; $i < 10; $i++) {
$expected[] = $nodes[($testindex + $i) % 10];
}
$this->assertEquals(
$expected,
$h->getNodes('key', 10));
}
public function testFallbackWhenANodeIsRemoved()
{
$h = new Horde_Support_ConsistentHash(array(), 1, 1);
// Create an array of random values and one fixed test value and sort
// them by their hashes
$nodes = array();
for ($i = 0; $i < 10; $i++) {
$val = uniqid(mt_rand(), true);
$nodes[$h->hash(serialize($val) . '0')] = $val;
}
$nodes[$h->hash(serialize('key'))] = 'key';
ksort($nodes);
// Remove the fixed test value.
$nodes = array_values($nodes);
$testindex = array_search('key', $nodes);
array_splice($nodes, $testindex, 1);
foreach ($nodes as $node) {
$h->add($node);
}
$this->assertEquals($h->get('key'), $nodes[$testindex]);
$h->remove($nodes[$testindex]);
$this->assertEquals($h->get('key'), $nodes[($testindex + 1) % 10]);
$h->remove($nodes[($testindex + 1) % 10]);
$this->assertEquals($h->get('key'), $nodes[($testindex + 2) % 10]);
}
}
Horde_Support-2.2.0/test/Horde/Support/GuidTest.php 0000664 0001750 0001750 00000002320 13055004475 020351 0 ustar jan jan 'localhost'));
$this->assertEquals(48, strlen($guid));
$this->assertRegExp('/\d{14}\.[-_0-9a-zA-Z]{23}@localhost/', (string)$guid);
}
public function testDuplicates()
{
$values = array();
for ($i = 0; $i < 10000; ++$i) {
$id = strval(new Horde_Support_Guid());
$this->assertArrayNotHasKey($id, $values);
$values[$id] = 1;
}
}
public function testOptions()
{
$this->assertStringEndsWith('example.com', (string)new Horde_Support_Guid(array('server' => 'example.com')));
$this->assertRegExp('/\d{14}\.prefix\.[-_0-9a-zA-Z]{23}@localhost/', (string)new Horde_Support_Guid(array('prefix' => 'prefix', 'server' => 'localhost')));
}
}
Horde_Support-2.2.0/test/Horde/Support/InflectorTest.php 0000664 0001750 0001750 00000020214 13055004475 021410 0 ustar jan jan 'sheep',
'man' => 'men',
'woman' => 'women',
'user' => 'users',
'foot' => 'feet',
'hive' => 'hives',
'chive' => 'chives',
'event' => 'events',
'task' => 'tasks',
'preference' => 'preferences',
'child' => 'children',
'moose' => 'moose',
'mouse' => 'mice',
);
public function setUp()
{
$this->inflector = new Horde_Support_Inflector;
}
public function testSingularizeAndPluralize()
{
foreach ($this->words as $singular => $plural) {
$this->assertEquals($plural, $this->inflector->pluralize($singular));
$this->assertEquals($singular, $this->inflector->singularize($plural));
}
}
public function testCamelize()
{
// underscore => camelize
$this->assertEquals('Test', $this->inflector->camelize('test'));
$this->assertEquals('TestCase', $this->inflector->camelize('test_case'));
$this->assertEquals('Test/Case', $this->inflector->camelize('test/case'));
$this->assertEquals('TestCase/Name', $this->inflector->camelize('test_case/name'));
// already camelized
$this->assertEquals('Test', $this->inflector->camelize('Test'));
$this->assertEquals('TestCase', $this->inflector->camelize('testCase'));
$this->assertEquals('TestCase', $this->inflector->camelize('TestCase'));
$this->assertEquals('Test/Case', $this->inflector->camelize('Test_Case'));
}
public function testCamelizeLower()
{
// underscore => camelize
$this->assertEquals('test', $this->inflector->camelize('test', 'lower'));
$this->assertEquals('testCase', $this->inflector->camelize('test_case', 'lower'));
$this->assertEquals('test/case', $this->inflector->camelize('test/case', 'lower'));
$this->assertEquals('testCase/name', $this->inflector->camelize('test_case/name', 'lower'));
// already camelized
$this->assertEquals('test', $this->inflector->camelize('Test', 'lower'));
$this->assertEquals('testCase', $this->inflector->camelize('testCase', 'lower'));
$this->assertEquals('testCase', $this->inflector->camelize('TestCase', 'lower'));
$this->assertEquals('test/case', $this->inflector->camelize('Test_Case', 'lower'));
}
public function testTitleize()
{
$this->markTestIncomplete();
}
/**
* data given to underscore() MUST be camelized already
*/
public function testUnderscore()
{
// most common scenarios (camelize => underscore)
$this->assertEquals('derek', $this->inflector->underscore('Derek'));
$this->assertEquals('dereks_test', $this->inflector->underscore('dereksTest'));
$this->assertEquals('dereks_test', $this->inflector->underscore('DereksTest'));
$this->assertEquals('dereks_test', $this->inflector->underscore('Dereks_Test'));
$this->assertEquals('dereks_name_test', $this->inflector->underscore('DereksName_Test'));
// not as common (already underscore)
$this->assertEquals('derek', $this->inflector->underscore('derek'));
$this->assertEquals('dereks_test', $this->inflector->underscore('dereks_test'));
}
public function testDasherize()
{
$this->assertEquals('derek', $this->inflector->dasherize('Derek'));
$this->assertEquals('dereks-test', $this->inflector->dasherize('dereksTest'));
$this->assertEquals('dereks-test', $this->inflector->dasherize('DereksTest'));
$this->assertEquals('dereks-test', $this->inflector->dasherize('Dereks_Test'));
$this->assertEquals('dereks-name-test', $this->inflector->dasherize('DereksName_Test'));
$this->assertEquals('derek', $this->inflector->dasherize('derek'));
$this->assertEquals('dereks-test', $this->inflector->dasherize('dereks_test'));
}
public function testHumanize()
{
// most common scenarios (column name => human)
$this->assertEquals('Derek', $this->inflector->humanize('derek'));
$this->assertEquals('Dereks test', $this->inflector->humanize('dereks_test'));
$this->assertEquals('Dereks test', $this->inflector->humanize('dereks_test_id'));
// not as common (columns are usually underscored)
$this->assertEquals('Derek', $this->inflector->humanize('Derek'));
$this->assertEquals('Dereks', $this->inflector->humanize('Dereks'));
$this->assertEquals('Dereks test', $this->inflector->humanize('dereksTest'));
$this->assertEquals('Dereks test', $this->inflector->humanize('dereksTestId'));
$this->assertEquals('Dereks test', $this->inflector->humanize('DereksTest'));
$this->assertEquals('Dereks test', $this->inflector->humanize('Dereks_Test'));
}
public function testDemodularize()
{
$this->assertEquals('Stuff', $this->inflector->demodulize('Fax_Job_Stuff'));
$this->assertEquals('Job', $this->inflector->demodulize('Fax_Job'));
$this->assertEquals('Fax', $this->inflector->demodulize('Fax'));
}
/**
* to table formatted string
*/
public function testTableize()
{
// most common scenarios (class => table)
$this->assertEquals('dereks', $this->inflector->tableize('Derek'));
$this->assertEquals('dereks', $this->inflector->tableize('Dereks'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('dereksTest'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('DereksTest'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('Dereks_Test'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('Dereks/Test'));
// not as common (already underscore)
$this->assertEquals('dereks', $this->inflector->tableize('derek'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('dereks_test'));
$this->assertEquals('dereks_tests', $this->inflector->tableize('dereks/test'));
}
/**
* to class formatted string
*/
public function testClassify()
{
$this->assertEquals('Derek', $this->inflector->classify('derek'));
$this->assertEquals('DereksTest', $this->inflector->classify('dereks_test'));
// not as common
$this->assertEquals('Derek', $this->inflector->classify('Derek'));
$this->assertEquals('Derek', $this->inflector->classify('Dereks'));
$this->assertEquals('DereksTest', $this->inflector->classify('dereksTest'));
$this->assertEquals('DereksTest', $this->inflector->classify('DereksTest'));
$this->assertEquals('Dereks_Test', $this->inflector->classify('Dereks_Test'));
}
public function testForeignKey()
{
$this->markTestIncomplete();
}
public function testOrdinalize()
{
$this->markTestIncomplete();
}
/*##########################################################################
# Inflection Cache
##########################################################################*/
// test setting inflection
public function testSetCache()
{
$this->inflector->setCache('documents', 'singularize', 'document');
$this->assertEquals('document', $this->inflector->getCache('documents', 'singularize'));
}
// test setting inflection
public function testClearCache()
{
$this->inflector->setCache('documents', 'singularize', 'document');
$this->inflector->clearCache();
$this->assertEquals(false, $this->inflector->getCache('documents', 'singularize'));
}
}
Horde_Support-2.2.0/test/Horde/Support/MemoryTest.php 0000664 0001750 0001750 00000002637 13055004475 020744 0 ustar jan jan assertInternalType('array', $t->push());
}
public function testMemoryEnd()
{
$t = new Horde_Support_Memory;
$t->push();
$this->assertInternalType('array', $t->pop());
}
public function testStartValues()
{
$t = new Horde_Support_Memory;
$this->assertEquals(4, count($t->push()));
}
public function testEndValues()
{
$t = new Horde_Support_Memory;
$t->push();
$this->assertEquals(4, count($t->pop()));
}
public function testOnlyIncrease()
{
$t = new Horde_Support_Memory;
$t->push();
$end = $t->pop();
$this->assertTrue($end[1] >= 0);
$this->assertTrue($end[3] >= 0);
}
public function testNotPushedThrowsException()
{
$t = new Horde_Support_Memory();
try {
$t->pop();
$this->fail('Expected Exception');
} catch (Exception $e) {}
}
}
Horde_Support-2.2.0/test/Horde/Support/ObjectStubTest.php 0000664 0001750 0001750 00000001355 13055004475 021534 0 ustar jan jan assertNull($stub->a);
$this->assertNull($php_errormsg);
ini_set('track_errors', $oldTrackErrors);
}
}
Horde_Support-2.2.0/test/Horde/Support/phpunit.xml 0000664 0001750 0001750 00000000056 13055004475 020325 0 ustar jan jan
Horde_Support-2.2.0/test/Horde/Support/RandomidTest.php 0000664 0001750 0001750 00000001411 13055004475 021216 0 ustar jan jan assertEquals(23, strlen(new Horde_Support_Randomid()));
}
public function testDuplicates()
{
$values = array();
for ($i = 0; $i < 10000; ++$i) {
$id = strval(new Horde_Support_Randomid());
$this->assertArrayNotHasKey($id, $values);
$values[$id] = 1;
}
}
}
Horde_Support-2.2.0/test/Horde/Support/StackTest.php 0000664 0001750 0001750 00000004142 13055004475 020532 0 ustar jan jan push('one');
$stack->push('two');
return $stack;
}
/**
* @depends testPushOnEmptyStack
*/
public function testPeekOnEmptyStack($stack)
{
$this->assertEquals('two', $stack->peek());
$this->assertEquals('two', $stack->peek(1));
$this->assertEquals('one', $stack->peek(2));
$this->assertNull($stack->peek(3));
$this->assertNull($stack->peek(0));
}
/**
* @depends testPushOnEmptyStack
*/
public function testPopFromEmptyStack($stack)
{
$this->assertEquals('two', $stack->pop());
$this->assertEquals('one', $stack->pop());
$this->assertNull($stack->pop());
}
public function testPrefilledConstructor()
{
return new Horde_Support_Stack(array('foo', 'bar'));
}
/**
* @depends testPrefilledConstructor
*/
public function testPeekOnPrefilledStack($stack)
{
$this->assertEquals('bar', $stack->peek(1));
$this->assertEquals('foo', $stack->peek(2));
}
/**
* @depends testPrefilledConstructor
*/
public function testPushOnPrefilledStack($stack)
{
$stack->push('baz');
return $stack;
}
/**
* @depends testPushOnPrefilledStack
*/
public function testPopFromPrefilledStack($stack)
{
$this->assertEquals('baz', $stack->pop());
$this->assertEquals('bar', $stack->pop());
$this->assertEquals('foo', $stack->pop());
$this->assertNull($stack->pop());
}
}
Horde_Support-2.2.0/test/Horde/Support/StringStreamTest.php 0000664 0001750 0001750 00000002023 13055004475 022103 0 ustar jan jan assertLessThan($memoryUsage + $bytes, $memoryUsage2);
$fp = $stream->fopen();
$memoryUsage3 = memory_get_usage();
$this->assertLessThan($memoryUsage + $bytes, $memoryUsage3);
while (!feof($fp)) { fread($fp, 1024); }
$memoryUsage4 = memory_get_usage();
$this->assertLessThan($memoryUsage + $bytes, $memoryUsage4);
}
}
Horde_Support-2.2.0/test/Horde/Support/StubTest.php 0000664 0001750 0001750 00000003300 13055004475 020375 0 ustar jan jan assertNull($stub->{uniqid()});
$this->assertNull($php_errormsg);
}
public function testAnyMethodIsCallable()
{
$stub = new Horde_Support_Stub;
$this->assertTrue(is_callable(array($stub, uniqid())));
$this->assertNull($stub->{uniqid()}());
}
public function testAnyStaticMethodIsCallable()
{
$this->assertTrue(is_callable(array('Horde_Support_Stub', uniqid())));
$unique = uniqid();
$this->assertNull(Horde_Support_Stub::$unique());
}
public function testToString()
{
$this->assertEquals('', (string)new Horde_Support_Stub());
}
public function testArrayAccess()
{
$stub = new Horde_Support_Stub();
// Set
$stub['foo'] = 'bar';
// Isset
$this->assertFalse(isset($stub['foo']));
// Get
$this->assertNull($stub['foo']);
// Count
$this->assertEquals(
0,
count($stub)
);
// Iteration
$this->assertEmpty(iterator_to_array($stub));
// Unset
unset($stub['foo']);
}
}
Horde_Support-2.2.0/test/Horde/Support/TimerTest.php 0000664 0001750 0001750 00000002010 13055004475 020535 0 ustar jan jan push();
$elapsed = $t->pop();
$this->assertTrue(is_float($start));
$this->assertTrue(is_float($elapsed));
$this->assertTrue($elapsed > 0);
}
/**
* test getting the finish time before starting the timer
*/
public function testNotStartedYetThrowsException()
{
$t = new Horde_Support_Timer();
try {
$t->pop();
$this->fail('Expected Exception');
} catch (Exception $e) {}
}
}
Horde_Support-2.2.0/test/Horde/Support/UuidTest.php 0000664 0001750 0001750 00000001375 13055004475 020400 0 ustar jan jan assertEquals(36, strlen(new Horde_Support_Uuid()));
}
public function testDuplicates()
{
$values = array();
for ($i = 0; $i < 10000; ++$i) {
$id = strval(new Horde_Support_Uuid());
$this->assertArrayNotHasKey($id, $values);
$values[$id] = 1;
}
}
}