/** * 指定されたキー名と値を関連づけます. * この実装では, 内部に保存されている配列に対して * <code> * $arr[$key] = $value; * </code> * を実行するのと同等の操作を行います. * もしも $key に非スカラー値 (オブジェクトや配列など) が指定された場合は, * {@link Values::stringValue} で string 型に変換した結果をキーとします. * * @param string $key キー名 * @param mixed $value 指定されたキーに関連づける値 */ public function put($key, $value) { if (!is_scalar($key)) { $key = Values::stringValue($key); } $this->data[$key] = $value; }
/** * 文字列内に含まれる {0}, {1}, {2} などのテンプレート変数を, $args 内の各要素で置き換えます. 例えば * <code> * template('My name is {0}. I am {1} years old', array('Taro', 18)); * </code> * の結果は次のようになります. * <code> * "My name is Taro. I am 18 years old" * </code> * * $template が NULL の場合は NULL を返します. * * @param string $template テンプレート * @param array $args 置き換える内容の配列 * @return string テンプレートの適用結果 */ public static function template($template, array $args = array()) { if ($template === null) { return null; } $subject = Values::stringValue($template); $replaces = array(); foreach ($args as $key => $value) { $from = "{" . $key . "}"; $replaces[$from] = $value; } return strtr($subject, $replaces); }
/** * stringValue() のテストです. * 以下を確認します. * * - __toString() が定義されているオブジェクトは, __toString() の結果を返す. * - __toString() が定義されていないオブジェクトは, クラス名を返す. * - スカラー値は strval() のアルゴリズムに基づいて文字列に変換する. * - リソース型の値は "resource_type #num" 形式の文字列となる. (例えば "stream #1") * * @covers Peach\Util\Values::stringValue */ public function testStringValue() { $obj = new ValuesTest_Object("asdf"); $std = new \stdClass(); $fp = fopen(__FILE__, "r"); // __toString() が定義されているオブジェクトは、呼び出した結果を返す $this->assertSame("test value=asdf", Values::stringValue($obj)); // __toString() が定義されていないオブジェクトはクラス名を返す $this->assertSame("stdClass", Values::stringValue($std)); // スカラー値は strval() のアルゴリズムに基づく $this->assertSame("hoge", Values::stringValue("hoge")); $this->assertSame("", Values::stringValue(null)); $this->assertSame("1", Values::stringValue(true)); $this->assertSame("0", Values::stringValue(0)); // リソース型は "resource_type #num" 形式の文字列 $this->assertStringStartsWith("stream #", Values::stringValue($fp)); }