package.xml0000664000175000017500000004750613055004476011317 0ustar janjan Horde_Support pear.horde.org Horde support package Support classes not tied to Horde but is used by it. These classes can be used outside of Horde as well. Chuck Hagenbuch chuck chuck@horde.org yes Jan Schneider jan jan@horde.org yes Michael Slusarz slusarz slusarz@horde.org yes 2017-02-27 2.2.0 2.2.0 stable stable BSD-2-Clause * [jan] Add Horde_Backtrace#createFromThrowable() to support PHP 7 error objects too. 5.3.0 8.0.0alpha1 8.0.0alpha1 1.7.0 Horde_Exception pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Stream_Wrapper pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Util pear.horde.org 2.0.0 3.0.0alpha1 3.0.0alpha1 Horde_Test pear.horde.org 2.1.0 3.0.0alpha1 3.0.0alpha1 0.1.0 0.1.0 beta beta 2010-07-10 BSD-2-Clause * Add Horde_Support_CombineStream. * Initial horde/support package * Initial Horde_Support_Array object * Initial Horde_Support_Backtrace object * Initial Horde_Support_ConsistentHash object * Initial Horde_Support_Inflector object * Initial Horde_Support_Stack object * Initial Horde_Support_StringStream object * Initial Horde_Support_Stub object * Initial Horde_Support_Timer object * Initial Horde_Support_Uuid object * Initial Horde_Support_Numerizer objects 1.0.0alpha1 1.0.0 alpha alpha 2011-03-08 BSD-2-Clause * First alpha release for Horde 4. * Add Horde_Support_Randomid. * Add Portuguese numerizer. 1.0.0beta1 1.0.0 beta beta 2011-03-16 BSD-2-Clause * First beta release for Horde 4. 1.0.0RC1 1.0.0 beta beta 2011-03-22 BSD-2-Clause * First release candidate for Horde 4. 1.0.0RC2 1.0.0 beta beta 2011-03-29 BSD-2-Clause * Second release candidate for Horde 4. 1.0.0 1.0.0 stable stable 2011-04-06 BSD-2-Clause * First stable release for Horde 4. 1.0.1 1.0.0 stable stable 2011-11-22 BSD-2-Clause * [jan] Fix tests to work with PHPUnit 3.6. 1.0.2 1.0.0 stable stable 2012-02-22 BSD-2-Clause * [mms] Fix failing unit tests. 2.0.0alpha1 1.1.0 alpha stable 2012-07-06 BSD-2-Clause * First alpha release for Horde 5. * [mms] Add Horde_Support_ObjectStub. 2.0.0beta1 1.1.0 beta stable 2012-07-19 BSD-2-Clause * First beta release for Horde 5. 2.0.0beta2 1.2.0 beta stable 2012-08-29 BSD-2-Clause * [jan] If creating Horde_Support_Backtrace from an Exception, include any previous exceptions. * [jan] Make Horde_Support_Backtrace#backtrace a public property. 2.0.0 1.2.0 stable stable 2012-10-30 BSD-2-Clause * First stable release for Horde 5. 2.0.1 1.2.0 stable stable 2012-11-06 BSD-2-Clause * [jan] Support uuid extension from OSSP (remi@famillecollet.com, Request #11653). 2.0.2 1.2.0 stable stable 2012-11-19 BSD-2-Clause * [mms] Better generation of random IDs. 2.0.3 1.2.0 stable stable 2013-01-29 BSD-2-Clause * [mms] Fix detection of sys_getloadavg() on Windows (Bug #11972). 2.0.4 1.2.0 stable stable 2013-03-05 BSD-2-Clause * [mms] Simplify Horde_Support_Array iterator. 2.1.0 2.1.0 stable stable 2013-04-08 BSD-2-Clause * [mms] Add Horde_Support_CaseInsensitiveArray class. * [mms] Add missing magic methods to Horde_Support_Stub. 2.1.1 2.1.0 stable stable 2013-09-02 BSD-2-Clause * [mms] Horde_Support_Stub now handles array-like accesses. 2.1.2 2.1.0 stable stable 2015-01-09 BSD-2-Clause * [jan] Add Composer definition. 2.1.3 2.1.0 stable stable 2015-04-28 BSD-2-Clause * [jan] Fix issues with certain locales like Turkish. 2.1.4 2.1.0 stable stable 2015-07-31 BSD-2-Clause * [jan] Fix Composer file. 2.1.5 2.1.0 stable stable 2016-02-02 BSD-2-Clause * [jan] Mark PHP 7 as supported. 2.2.0 2.2.0 stable stable 2017-02-27 BSD-2-Clause * [jan] Add Horde_Backtrace#createFromThrowable() to support PHP 7 error objects too. Horde_Support-2.2.0/doc/Horde/Support/COPYING0000664000175000017500000000243013055004475016733 0ustar janjan Copyright 1999-2017 Horde LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HORDE PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Horde_Support-2.2.0/doc/horde.yml0000664000175000017500000000027513055004475015014 0ustar janjan--- id: Support name: Support full: Supporting library description: > Support classes not tied to Horde but is used by it. These classes can be used outside of Horde as well. list: dev Horde_Support-2.2.0/lib/Horde/Support/Numerizer/Locale/Base.php0000664000175000017500000001111413055004475022442 0ustar janjan * @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_Locale_Base { public $DIRECT_NUMS = array( 'eleven' => '11', 'twelve' => '12', 'thirteen' => '13', 'fourteen' => '14', 'fifteen' => '15', 'sixteen' => '16', 'seventeen' => '17', 'eighteen' => '18', 'nineteen' => '19', 'ninteen' => '19', // Common mis-spelling 'zero' => '0', 'one' => '1', 'two' => '2', 'three' => '3', 'four(\W|$)' => '4$1', // The weird regex is so that it matches four but not fourty 'five' => '5', 'six(\W|$)' => '6$1', 'seven(\W|$)' => '7$1', 'eight(\W|$)' => '8$1', 'nine(\W|$)' => '9$1', 'ten' => '10', '\ba[\b^$]' => '1', // doesn't make sense for an 'a' at the end to be a 1 ); public $TEN_PREFIXES = array( 'twenty' => 20, 'thirty' => 30, 'forty' => 40, 'fourty' => 40, // Common mis-spelling 'fifty' => 50, 'sixty' => 60, 'seventy' => 70, 'eighty' => 80, 'ninety' => 90, 'ninty' => 90, // Common mis-spelling ); public $BIG_PREFIXES = array( 'hundred' => 100, 'thousand' => 1000, 'million' => 1000000, 'billion' => 1000000000, 'trillion' => 1000000000000, ); public function numerize($string) { // preprocess $string = $this->_splitHyphenatedWords($string); $string = $this->_hideAHalf($string); $string = $this->_directReplacements($string); $string = $this->_replaceTenPrefixes($string); $string = $this->_replaceBigPrefixes($string); $string = $this->_fractionalAddition($string); return $string; } /** * will mutilate hyphenated-words but shouldn't matter for date extraction */ protected function _splitHyphenatedWords($string) { return preg_replace('/ +|([^\d])-([^d])/', '$1 $2', $string); } /** * take the 'a' out so it doesn't turn into a 1, save the half for the end */ protected function _hideAHalf($string) { return str_replace('a half', 'haAlf', $string); } /** * easy/direct replacements */ protected function _directReplacements($string) { foreach ($this->DIRECT_NUMS as $dn => $dn_replacement) { $string = preg_replace("/$dn/i", $dn_replacement, $string); } return $string; } /** * ten, twenty, etc. */ protected function _replaceTenPrefixes($string) { foreach ($this->TEN_PREFIXES as $tp => $tp_replacement) { $string = preg_replace_callback( "/(?:$tp)( *\d(?=[^\d]|\$))*/i", function ($m) use ($tp_replacement) { return $tp_replacement + (isset($m[1]) ? (int)$m[1] : 0); }, $string ); } return $string; } /** * hundreds, thousands, millions, etc. */ protected function _replaceBigPrefixes($string) { foreach ($this->BIG_PREFIXES as $bp => $bp_replacement) { $string = preg_replace_callback( '/(\d*) *' . $bp . '/i', function ($m) use ($bp_replacement) { return $bp_replacement * (int)$m[1]; }, $string ); $string = $this->_andition($string); } return $string; } protected function _andition($string) { while (true) { if (preg_match('/(\d+)( | and )(\d+)(?=[^\w]|$)/i', $string, $sc, PREG_OFFSET_CAPTURE)) { if (preg_match('/and/', $sc[2][0]) || (strlen($sc[1][0]) > strlen($sc[3][0]))) { $string = substr($string, 0, $sc[1][1]) . ((int)$sc[1][0] + (int)$sc[3][0]) . substr($string, $sc[3][1] + strlen($sc[3][0])); continue; } } break; } return $string; } protected function _fractionalAddition($string) { return preg_replace_callback( '/(\d+)(?: | and |-)*haAlf/i', function ($m) { return (string)((float)$m[1] + 0.5); }, $string ); } } Horde_Support-2.2.0/lib/Horde/Support/Numerizer/Locale/De.php0000664000175000017500000000734613055004475022134 0ustar janjan * @author Jan Schneider * @license http://www.horde.org/licenses/bsd BSD * @category Horde * @package Support */ /** * @author Chuck Hagenbuch * @author Jan Schneider * @license http://www.horde.org/licenses/bsd BSD * @category Horde * @package Support */ class Horde_Support_Numerizer_Locale_De extends Horde_Support_Numerizer_Locale_Base { public $DIRECT_NUMS = array( 'dreizehn' => 13, 'vierzehn' => 14, 'fünfzehn' => 15, 'sechzehn' => 16, 'siebzehn' => 17, 'achtzehn' => 18, 'neunzehn' => 19, 'ein[se]?' => 1, 'zwei' => 2, 'zwo' => 2, 'drei' => 3, 'vier' => 4, 'fünf' => 5, 'sechs' => 6, 'sieben' => 7, 'acht' => 8, 'neun' => 9, 'zehn' => 10, 'elf' => 11, 'zwölf' => 12, ); public $TEN_PREFIXES = array( 'zwanzig' => 20, 'dreißig' => 30, 'vierzig' => 40, 'fünfzig' => 50, 'sechzig' => 60, 'siebzig' => 70, 'achtzig' => 80, 'neunzig' => 90, ); public $BIG_PREFIXES = array( 'hundert' => 100, 'tausend' => 1000, 'million *' => 1000000, 'milliarde *' => 1000000000, 'billion *' => 1000000000000, ); /** * Rules: * * - there are irregular word for 11 and 12 like in English * - numbers below one million are written together (1 M = "eine Million", 100 = "einhundert") * - "a" is declinable (see above, "one" = "eins", "a" = "ein/eine") * - numbers below 100 are flipped compared to english, and have an "and = "und" (21 = "twenty-one" = "einundzwanzig") */ public function numerize($string) { $string = $this->_replaceTenPrefixes($string); $string = $this->_directReplacements($string); $string = $this->_replaceBigPrefixes($string); $string = $this->_fractionalAddition($string); return $string; } /** * ten, twenty, etc. */ protected function _replaceTenPrefixes($string) { foreach ($this->TEN_PREFIXES as $tp => $tp_replacement) { $string = preg_replace_callback( "/(?:$tp)( *\d(?=[^\d]|\$))*/i", function ($m) use ($tp_replacement) { return $tp_replacement + (isset($m[1]) ? (int)$m[1] : 0); }, $string ); } return $string; } /** * hundreds, thousands, millions, etc. */ protected function _replaceBigPrefixes($string) { foreach ($this->BIG_PREFIXES as $bp => $bp_replacement) { $string = preg_replace_callback( '/(\d*) *' . $bp . '(\d?)/i', function ($m) use ($bp_replacement) { $factor = (int)$m[1]; if (!$factor) { $factor = 1; } return ($bp_replacement * $factor) . ($bp_replacement == 100 ? ($m[2] ? 'und' : '') : 'und') . $m[2]; }, $string ); $string = $this->_andition($string); } return $string; } protected function _andition($string) { while (preg_match('/(\d+)((?: *und *)+)(\d*)(?=\w|$)/i', $string, $sc, PREG_OFFSET_CAPTURE)) { $string = substr($string, 0, $sc[1][1]) . ((int)$sc[1][0] + (int)$sc[3][0]) . substr($string, $sc[3][1] + strlen($sc[3][0])); } return $string; } } Horde_Support-2.2.0/lib/Horde/Support/Numerizer/Locale/Pt.php0000664000175000017500000001007713055004475022162 0ustar janjan '13', 'catorze' => '14', 'quatorze' => '14', 'quinze' => '15', 'dezasseis' => '16', 'dezassete' => '17', 'dezoito' => '18', 'dezanove' => '19', 'um(\W|$)' => '1$1', 'uma(\W|$)' => '1$1', 'dois' => '2', 'duas' => '2', 'tres' => '3', 'quatro' => '4', 'cinco' => '5', 'seis' => '6', 'sete' => '7', 'oito' => '8', 'nove' => '9', 'dez' => '10', 'onze' => '11', 'doze' => '12', ); public $TEN_PREFIXES = array( 'vinte' => '20', 'trinta' => '30', 'quarenta' => '40', 'cinquenta' => '50', 'sessenta' => '60', 'setenta' => '70', 'oitenta' => '80', 'noventa' => '90', ); public $BIG_PREFIXES = array( 'cem' => '100', 'mil' => '1000', 'milhao *' => '1000000', 'milhar de *' => '1000000000', 'biliao *' => '1000000000000', ); public function numerize($string) { // preprocess $string = $this->_splitHyphenateWords($string); $string = $this->_replaceTenPrefixes($string); $string = $this->_directReplacements($string); $string = $this->_replaceBigPrefixes($string); // $string = $this->_fractionalAddition($string); return $string; } /** * will mutilate hyphenated-words but shouldn't matter for date extraction */ protected function _splitHyphenateWords($string) { return preg_replace('/ +|([^\d]) e? ([^d])/', '$1 $2', $string); } /** * easy/direct replacements */ protected function _directReplacements($string) { foreach ($this->DIRECT_NUMS as $dn => $dn_replacement) { $string = preg_replace("/$dn/i", $dn_replacement, $string); } return $string; } /** * ten, twenty, etc. */ protected function _replaceTenPrefixes($string) { foreach ($this->TEN_PREFIXES as $tp => $tp_replacement) { $string = preg_replace_callback( "/(?:$tp)( *\d(?=[^\d]|\$))*/i", function ($m) use ($tp_replacement) { return $tp_replacement + (isset($m[1]) ? (int)$m[1] : 0); }, $string ); } return $string; } /** * hundreds, thousands, millions, etc. */ protected function _replaceBigPrefixes($string) { foreach ($this->BIG_PREFIXES as $bp => $bp_replacement) { $string = preg_replace_callback( '/(\d*) *' . $bp . '(\d?)/i', function ($m) use ($bp_replacement) { $factor = (int)$m[1]; if (!$factor) { $factor = 1; } return ($bp_replacement * $factor) . ($bp_replacement == 100 ? ($m[2] ? 'e' : '') : 'e') . $m[2]; }, $string); $string = $this->_andition($string); } return $string; } protected function _andition($string) { while (preg_match('/(\d+)((?: *e *)+)(\d*)(?=\w|$)/i', $string, $sc, PREG_OFFSET_CAPTURE)) { $string = substr($string, 0, $sc[1][1]) . ((int)$sc[1][0] + (int)$sc[3][0]) . substr($string, $sc[3][1] + strlen($sc[3][0])); } return $string; } protected function _fractionalAddition($string) { return preg_replace_callback( '/(\d+)(?: | e |-)*/i', function ($m) { return (string)((float)$m[1] + 0.5); }, $string ); } } Horde_Support-2.2.0/lib/Horde/Support/Array.php0000664000175000017500000001034213055004475017471 0ustar janjanupdate($vars); } } /** */ public function get($key, $default = null) { return isset($this->_array[$key]) ? $this->_array[$key] : $default; } /** * Gets the value at $offset. If no value exists at that offset, or the * value $offset is NULL, then $default is set as the value of $offset. * * @param string $offset Offset to retrieve and set if unset * @param string $default Default value if $offset does not exist * * @return mixed Value at $offset or $default */ public function getOrSet($offset, $default = null) { $value = $this->offsetGet($offset); if (is_null($value)) { $this->offsetSet($offset, $value = $default); } return $value; } /** * Gets the value at $offset and deletes it from the array. If no value * exists at $offset, or the value at $offset is null, then $default * will be returned. * * @param string $offset Offset to pop * @param string $default Default value * * @return mixed Value at $offset or $default */ public function pop($offset, $default = null) { $value = $this->offsetGet($offset); $this->offsetUnset($offset); return isset($value) ? $value : $default; } /** * Update the array with the key/value pairs from $array * * @param array $array Key/value pairs to set/change in the array. */ public function update($array) { if (!is_array($array) && !$array instanceof Traversable) { throw new InvalidArgumentException('expected array or traversable, got ' . gettype($array)); } foreach ($array as $key => $val) { $this->offsetSet($key, $val); } } /** * Get the keys in the array * * @return array */ public function getKeys() { return array_keys($this->_array); } /** * Get the values in the array * * @return array */ public function getValues() { return array_values($this->_array); } /** * Clear out the array */ public function clear() { $this->_array = array(); } /** */ public function __get($key) { return $this->get($key); } /** */ public function __set($key, $value) { $this->_array[$key] = $value; } /** * Checks the existance of $key in this array */ public function __isset($key) { return array_key_exists($key, $this->_array); } /** * Removes $key from this array */ public function __unset($key) { unset($this->_array[$key]); } /** * Count the number of elements * * @return integer */ public function count() { return count($this->_array); } /** */ public function getIterator() { return new ArrayIterator($this->_array); } /** * Gets the value of $offset in this array * * @see __get() */ public function offsetGet($offset) { return $this->__get($offset); } /** * Sets the value of $offset to $value * * @see __set() */ public function offsetSet($offset, $value) { return $this->__set($offset, $value); } /** * Checks the existence of $offset in this array * * @see __isset() */ public function offsetExists($offset) { return $this->__isset($offset); } /** * Removes $offset from this array * * @see __unset() */ public function offsetUnset($offset) { return $this->__unset($offset); } } Horde_Support-2.2.0/lib/Horde/Support/Backtrace.php0000664000175000017500000001145213055004475020275 0ustar janjancreateFromThrowable($backtrace); } elseif ($backtrace instanceof Exception) { $this->createFromException($backtrace); } elseif ($backtrace) { $this->createFromDebugBacktrace($backtrace); } else { $this->createFromDebugBacktrace(debug_backtrace(), 1); } } /** * Wraps the result of debug_backtrace(). * * By specifying a non-zero $nestingLevel, levels of the backtrace can be * ignored. For instance, when Horde_Support_Backtrace creates a backtrace * for you, it ignores the Horde_Backtrace constructor in the wrapped * trace. * * @param array $backtrace The debug_backtrace() result. * @param integer $nestingLevel The number of levels of the backtrace to * ignore. */ public function createFromDebugBacktrace($backtrace, $nestingLevel = 0) { while ($nestingLevel > 0) { array_shift($backtrace); --$nestingLevel; } $this->backtrace = $backtrace; } /** * Wraps an error object's backtrace. * * @since Horde_Support 2.2.0 * * @param Throwable $e The error to wrap. */ public function createFromThrowable(Throwable $e) { $this->_createFromThrowable($e); } /** * Wraps an error object's backtrace. * * @todo Merge with createFromThrowable with PHP 7. * * @param Throwable $e The error to wrap. */ protected function _createFromThrowable($e) { $this->backtrace = $e->getTrace(); if ($previous = $e->getPrevious()) { $backtrace = new self($previous); $this->backtrace = array_merge($backtrace->backtrace, $this->backtrace); } } /** * Wraps an Exception object's backtrace. * * @todo Remove with PHP 7. * * @param Exception $e The exception to wrap. */ public function createFromException(Exception $e) { $this->_createFromThrowable($e); } /** * Returns the nesting level (number of calls deep) of the current context. * * @return integer Nesting level. */ public function getNestingLevel() { return count($this->backtrace); } /** * Returns the context at a specific nesting level. * * @param integer $nestingLevel 0 == current level, 1 == caller, and so on * * @return array The requested context. */ public function getContext($nestingLevel) { if (!isset($this->backtrace[$nestingLevel])) { throw new Horde_Exception('Unknown nesting level'); } return $this->backtrace[$nestingLevel]; } /** * Returns details about the routine where the exception occurred. * * @return array $caller */ public function getCurrentContext() { return $this->getContext(0); } /** * Returns details about the caller of the routine where the exception * occurred. * * @return array $caller */ public function getCallingContext() { return $this->getContext(1); } /** * Returns a simple, human-readable list of the complete backtrace. * * @return string The backtrace map. */ public function __toString() { $count = count($this->backtrace); $pad = strlen($count); $map = ''; for ($i = $count - 1; $i >= 0; $i--) { $map .= str_pad($count - $i, $pad, ' ', STR_PAD_LEFT) . '. '; if (isset($this->backtrace[$i]['class'])) { $map .= $this->backtrace[$i]['class'] . $this->backtrace[$i]['type']; } $map .= $this->backtrace[$i]['function'] . '()'; if (isset($this->backtrace[$i]['file'])) { $map .= ' ' . $this->backtrace[$i]['file'] . ':' . $this->backtrace[$i]['line']; } $map .= "\n"; } return $map; } } Horde_Support-2.2.0/lib/Horde/Support/CaseInsensitiveArray.php0000664000175000017500000000377313055004475022520 0ustar janjan * @category Horde * @copyright 2013-2017 Horde LLC * @license http://www.horde.org/licenses/bsd BSD * @package Support */ class Horde_Support_CaseInsensitiveArray extends ArrayIterator { /** */ public function offsetGet($offset) { return (is_null($offset = $this->_getRealOffset($offset))) ? null : parent::offsetGet($offset); } /** */ public function offsetSet($offset, $value) { if (is_null($roffset = $this->_getRealOffset($offset))) { parent::offsetSet($offset, $value); } else { parent::offsetSet($roffset, $value); } } /** */ public function offsetExists($offset) { return !is_null($offset = $this->_getRealOffset($offset)); } /** */ public function offsetUnset($offset) { if (!is_null($offset = $this->_getRealOffset($offset))) { parent::offsetUnset($offset); } } /** * Determines the actual array offset given the input offset. * * @param string $offset Input offset. * * @return string Real offset or null. */ protected function _getRealOffset($offset) { /* Optimize: check for base $offset in array first. */ if (parent::offsetExists($offset)) { return $offset; } foreach (array_keys($this->getArrayCopy()) as $key) { if (strcasecmp($key, $offset) === 0) { return $key; } } return null; } } Horde_Support-2.2.0/lib/Horde/Support/CombineStream.php0000664000175000017500000000420513055004475021144 0ustar janjan * @license http://www.horde.org/licenses/bsd BSD * @category Horde * @package Support */ /** * Provides access to the Combine stream wrapper. * * @author Michael Slusarz * @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.php0000664000175000017500000001511613055004475021354 0ustar janjan_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.php0000664000175000017500000000337113055004475017307 0ustar janjan * $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.php0000664000175000017500000003053113055004475020342 0ustar janjan '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.php0000664000175000017500000000522213055004475017664 0ustar janjan * $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.php0000664000175000017500000000252713055004475020401 0ustar janjan * @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.php0000664000175000017500000000235613055004475020465 0ustar janjan * @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.php0000664000175000017500000000332213055004475020150 0ustar janjan * $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.php0000664000175000017500000000144613055004475017465 0ustar janjan_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.php0000664000175000017500000000437113055004475021042 0ustar janjan * @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.php0000664000175000017500000000502713055004475017334 0ustar janjan * $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.php0000664000175000017500000000444313055004475017326 0ustar janjan * $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.php0000664000175000017500000000506613055004475023524 0ustar janjan '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.php0000664000175000017500000000530313055004475023174 0ustar janjan '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.php0000664000175000017500000000013213055004475020353 0ustar janjanrun(); Horde_Support-2.2.0/test/Horde/Support/ArrayTest.php0000664000175000017500000001347013055004475020547 0ustar janjanassertInstanceOf('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.php0000664000175000017500000000557513055004475021357 0ustar janjangetCurrentContext(); $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.php0000664000175000017500000000014313055004475020637 0ustar janjanassertInstanceOf($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.php0000664000175000017500000000237413055004475022222 0ustar janjanfopen(); $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.php0000664000175000017500000001744513055004475022434 0ustar janjanassertEquals(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.php0000664000175000017500000000232013055004475020351 0ustar janjan '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.php0000664000175000017500000002021413055004475021410 0ustar janjan '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.php0000664000175000017500000000263713055004475020744 0ustar janjanassertInternalType('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.php0000664000175000017500000000135513055004475021534 0ustar janjanassertNull($stub->a); $this->assertNull($php_errormsg); ini_set('track_errors', $oldTrackErrors); } } Horde_Support-2.2.0/test/Horde/Support/phpunit.xml0000664000175000017500000000005613055004475020325 0ustar janjan Horde_Support-2.2.0/test/Horde/Support/RandomidTest.php0000664000175000017500000000141113055004475021216 0ustar janjanassertEquals(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.php0000664000175000017500000000414213055004475020532 0ustar janjanpush('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.php0000664000175000017500000000202313055004475022103 0ustar janjanassertLessThan($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.php0000664000175000017500000000330013055004475020375 0ustar janjanassertNull($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.php0000664000175000017500000000201013055004475020535 0ustar janjanpush(); $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.php0000664000175000017500000000137513055004475020400 0ustar janjanassertEquals(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; } } }