/** * @param mixed $default * @throws AssertionFailed * @throws \Exception */ private function guardDefault($default) { if ($this->isASingleValue()) { $this->guardValue($default); return; } Assertion::nullOrIsArray($default, sprintf('Field [%s] default must be an array.', $this->name)); if (null === $default) { return; } if ($this->isAMap()) { Assertion::true(ArrayUtils::isAssoc($default), sprintf('Field [%s] default must be an associative array.', $this->name)); } foreach ($default as $k => $v) { Assertion::notNull($v, sprintf('Field [%s] default for key [%s] cannot be null.', $this->name, $k)); $this->guardValue($v); } }
/** * @param array $data * @return Message * * @throws \Exception * @throws GdbotsPbjException */ private function doDeserialize(array $data) { $schemaId = SchemaId::fromString((string) $data[Schema::PBJ_FIELD_NAME]); $className = MessageResolver::resolveId($schemaId); /** @var Message $message */ $message = new $className(); Assertion::isInstanceOf($message, 'Gdbots\\Pbj\\Message'); if ($message::schema()->getCurieMajor() !== $schemaId->getCurieMajor()) { throw new InvalidResolvedSchema($message::schema(), $schemaId, $className); } $schema = $message::schema(); foreach ($data as $fieldName => $value) { if (!$schema->hasField($fieldName)) { continue; } if (null === $value) { $message->clear($fieldName); continue; } $field = $schema->getField($fieldName); $type = $field->getType(); switch ($field->getRule()->getValue()) { case FieldRule::A_SINGLE_VALUE: $message->set($fieldName, $type->decode($value, $field, $this)); break; case FieldRule::A_SET: case FieldRule::A_LIST: Assertion::isArray($value, sprintf('Field [%s] must be an array.', $fieldName), $fieldName); $values = []; foreach ($value as $v) { $values[] = $type->decode($v, $field, $this); } if ($field->isASet()) { $message->addToSet($fieldName, $values); } else { $message->addToList($fieldName, $values); } break; case FieldRule::A_MAP: Assertion::true(ArrayUtils::isAssoc($value), sprintf('Field [%s] must be an associative array.', $fieldName), $fieldName); foreach ($value as $k => $v) { $message->addToMap($fieldName, $k, $type->decode($v, $field, $this)); } break; default: break; } } return $message->set(Schema::PBJ_FIELD_NAME, $schema->getId()->toString())->populateDefaults(); }