StringUtil.php (2540B)
1 <?php 2 3 /* 4 * This file is part of the Prophecy. 5 * (c) Konstantin Kudryashov <ever.zet@gmail.com> 6 * Marcello Duarte <marcello.duarte@gmail.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12 namespace Prophecy\Util; 13 14 use Prophecy\Call\Call; 15 16 /** 17 * String utility. 18 * 19 * @author Konstantin Kudryashov <ever.zet@gmail.com> 20 */ 21 class StringUtil 22 { 23 /** 24 * Stringifies any provided value. 25 * 26 * @param mixed $value 27 * @param boolean $exportObject 28 * 29 * @return string 30 */ 31 public function stringify($value, $exportObject = true) 32 { 33 if (is_array($value)) { 34 if (range(0, count($value) - 1) === array_keys($value)) { 35 return '['.implode(', ', array_map(array($this, __FUNCTION__), $value)).']'; 36 } 37 38 $stringify = array($this, __FUNCTION__); 39 40 return '['.implode(', ', array_map(function ($item, $key) use ($stringify) { 41 return (is_integer($key) ? $key : '"'.$key.'"'). 42 ' => '.call_user_func($stringify, $item); 43 }, $value, array_keys($value))).']'; 44 } 45 if (is_resource($value)) { 46 return get_resource_type($value).':'.$value; 47 } 48 if (is_object($value)) { 49 return $exportObject ? ExportUtil::export($value) : sprintf('%s:%s', get_class($value), spl_object_hash($value)); 50 } 51 if (true === $value || false === $value) { 52 return $value ? 'true' : 'false'; 53 } 54 if (is_string($value)) { 55 $str = sprintf('"%s"', str_replace("\n", '\\n', $value)); 56 57 if (50 <= strlen($str)) { 58 return substr($str, 0, 50).'"...'; 59 } 60 61 return $str; 62 } 63 if (null === $value) { 64 return 'null'; 65 } 66 67 return (string) $value; 68 } 69 70 /** 71 * Stringifies provided array of calls. 72 * 73 * @param Call[] $calls Array of Call instances 74 * 75 * @return string 76 */ 77 public function stringifyCalls(array $calls) 78 { 79 $self = $this; 80 81 return implode(PHP_EOL, array_map(function (Call $call) use ($self) { 82 return sprintf(' - %s(%s) @ %s', 83 $call->getMethodName(), 84 implode(', ', array_map(array($self, 'stringify'), $call->getArguments())), 85 str_replace(GETCWD().DIRECTORY_SEPARATOR, '', $call->getCallPlace()) 86 ); 87 }, $calls)); 88 } 89 }