public function testNormalizeToArray() { $normalized = ArrayUtil::normalizeToArray($this->arrayTemplate, $this->arrayOld); $tmplKeys = array_keys($this->arrayTemplate); $oldKeys = array_keys($this->arrayOld); $keepKeys = array_intersect($tmplKeys, $oldKeys); $newKeys = array_diff($tmplKeys, $oldKeys); $deleteKeys = array_diff($oldKeys, $tmplKeys); // All keys in the template must be present: foreach ($tmplKeys as $key) { $this->assertArrayHasKey($key, $normalized, "Array lost a key!"); } // All fields not specified must be removed: foreach ($deleteKeys as $key) { $this->assertArrayNotHasKey($key, $normalized); } // All new fields must inherit specified default values: foreach ($newKeys as $key) { $this->assertEquals($this->arrayTemplate[$key], $normalized[$key], "Didn't inherit default value!"); } // All fields must retain their original values, if they didn't need to // be initialized with default values: foreach ($keepKeys as $key) { $this->assertEquals($this->arrayOld[$key], $normalized[$key], "Array value changed when it shouldn't have!"); } }
public function testUnpackAttribute() { $model = new CActiveMock(); $model->foo = CJSON::encode($this->arrayOld); $jfb = new NormalizedJSONFieldsBehavior(); $jfb->transformAttributes = array('foo' => array_keys($this->arrayTemplate)); $jfb->attach($model); $template = array_fill_keys(array_keys($this->arrayTemplate), null); $expected = ArrayUtil::normalizeToArray($template, $this->arrayOld); $model->raiseEvent('onAfterSave', new CModelEvent($model)); $this->assertEquals($expected, $model->foo); }
/** * Merges records of different types * @param array $recordArrs <type> => <array of records> * @param array $attrUnion Union of attribute names of each record type * @return array An array of records with keys equal to the keys specified in $attrUnion and * with values corresponding to the values in $recordArrs. If a particular record type in * $recordArrs does not have one of the attributes in $attrUnion, that attribute will be set * to null; */ public static function mergeMixedRecords(array $recordArrs, array $attrUnion) { $recordTemplate = array(); foreach ($attrUnion as $attr) { $recordTemplate[$attr] = null; } $combinedRecords = array(); foreach ($recordArrs as $recordType => $arr) { foreach ($arr as $record) { $combinedRecords[] = array_merge(ArrayUtil::normalizeToArray($recordTemplate, $record), array('recordType' => $recordType)); } } return $combinedRecords; }