本文整理汇总了PHP中Nette\PhpGenerator\ClassType::getNamespace方法的典型用法代码示例。如果您正苦于以下问题:PHP ClassType::getNamespace方法的具体用法?PHP ClassType::getNamespace怎么用?PHP ClassType::getNamespace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Nette\PhpGenerator\ClassType
的用法示例。
在下文中一共展示了ClassType::getNamespace方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: createFileOnDir
public function createFileOnDir(Local $adapter)
{
$outFile = str_replace('\\', '/', $this->currentClass->getNamespace()->getName() . '\\' . $this->currentClass->getName()) . '.php';
$this->_createFileOnDir($adapter, $outFile);
}
示例2: createOutputFileName
public function createOutputFileName(Type $type, ClassType $class)
{
if ($this->outputPath !== null) {
return rtrim($this->outputPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . str_replace("\\", DIRECTORY_SEPARATOR, $class->getNamespace()->getName()) . DIRECTORY_SEPARATOR . $class->getName() . ".php";
} else {
return dirname($type->getFileName()) . DIRECTORY_SEPARATOR . "Meta" . DIRECTORY_SEPARATOR . $class->getName() . ".php";
}
}
示例3: onGenerate
public function onGenerate(AbstractMetaSpec $spec, MetaSpecMatcher $matcher, Type $type, ClassType $class)
{
$ns = $class->getNamespace();
$ns->addUse("Skrz\\Meta\\XML\\XmlMetaInterface");
$ns->addUse($type->getName(), null, $typeAlias);
$class->addImplement("Skrz\\Meta\\XML\\XmlMetaInterface");
$groups = array();
$i = 0;
$valueGroupIdMask = 0;
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\XML\\XmlAnnotationInterface") as $xmlAnnotation) {
/** @var XmlAnnotationInterface $xmlAnnotation */
if (!isset($groups[$xmlAnnotation->getGroup()])) {
$groups[$xmlAnnotation->getGroup()] = 1 << $i++;
}
if ($xmlAnnotation instanceof XmlValue) {
$valueGroupIdMask |= $groups[$xmlAnnotation->getGroup()];
}
}
}
$class->addProperty("xmlGroups", $groups)->setStatic(true);
// fromXml()
$fromXml = $class->addMethod("fromXml");
$fromXml->setStatic(true);
$fromXml->addParameter("xml");
$fromXml->addParameter("group")->setOptional(true);
$fromXml->addParameter("object")->setOptional(true);
$fromXml->addComment("Creates \\{$type->getName()} from XML")->addComment("")->addComment("@param \\XMLReader|\\DOMElement \$xml")->addComment("@param string \$group")->addComment("@param {$typeAlias} \$object")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return {$typeAlias}");
$fromXml->addBody("if (!isset(self::\$xmlGroups[\$group])) {")->addBody("\tthrow new \\InvalidArgumentException('Group \\'' . \$group . '\\' not supported for ' . " . var_export($type->getName(), true) . " . '.');")->addBody("} else {")->addBody("\t\$id = self::\$xmlGroups[\$group];")->addBody("}")->addBody("")->addBody("if (\$object === null) {")->addBody("\t\$object = new {$typeAlias}();")->addBody("} elseif (!(\$object instanceof {$typeAlias})) {")->addBody("\tthrow new \\InvalidArgumentException('You have to pass object of class {$type->getName()}.');")->addBody("}")->addBody("")->addBody("if (\$xml instanceof \\XMLReader) {")->addBody("\treturn self::fromXmlReader(\$xml, \$group, \$id, \$object);")->addBody("} elseif (\$xml instanceof \\DOMElement) {")->addBody("\treturn self::fromXmlElement(\$xml, \$group, \$id, \$object);")->addBody("} else {")->addBody("\tthrow new \\InvalidArgumentException('Expected XMLReader or DOMElement, got ' . gettype(\$xml) . (is_object(\$xml) ? ' of class ' . get_class(\$xml) : '') . '.');")->addBody("}");
$fromXmlReader = $class->addMethod("fromXmlReader");
$fromXmlReader->setStatic(true)->setVisibility("private");
$fromXmlReader->addParameter("xml")->setTypeHint("\\XMLReader");
$fromXmlReader->addParameter("group");
$fromXmlReader->addParameter("id");
$fromXmlReader->addParameter("object")->setTypeHint($type->getName());
$fromXmlReader->addBody("if (\$xml->nodeType !== \\XMLReader::ELEMENT) {")->addBody("\tthrow new \\InvalidArgumentException('Expects XMLReader to be positioned on ELEMENT node.');")->addBody("}")->addBody("");
$attributesByName = array();
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\XML\\XmlAttribute") as $xmlAttribute) {
/** @var XmlAttribute $xmlAttribute */
$groupId = $groups[$xmlAttribute->group];
$name = strtolower($xmlAttribute->name);
if (!isset($attributesByName[$name])) {
$attributesByName[$name] = "";
}
$attributesByName[$name] .= "if ((\$id & {$groupId}) > 0 && \$xml->namespaceURI === " . var_export($xmlAttribute->namespace, true) . ") {\n";
$attributesByName[$name] .= Strings::indent($this->assignObjectProperty($xmlAttribute, $property, "\$xml->value"), 1, "\t") . "\n";
$attributesByName[$name] .= "}\n";
}
}
if (!empty($attributesByName)) {
$fromXmlReader->addBody("if (\$xml->moveToFirstAttribute()) {")->addBody("\tdo {")->addBody("\t\tswitch (strtolower(\$xml->localName)) {");
$i = 0;
foreach ($attributesByName as $name => $code) {
$fromXmlReader->addBody("\t\t\tcase " . var_export($name, true) . ":")->addBody(Strings::indent($code, 4, "\t"))->addBody("\t\t\t\tbreak;");
if ($i < count($attributesByName) - 1) {
$fromXmlReader->addBody("");
}
++$i;
}
$fromXmlReader->addBody("\t\t}")->addBody("\t} while (\$xml->moveToNextAttribute());")->addBody("")->addBody("\t\$xml->moveToElement();")->addBody("}")->addBody("");
}
$fromXmlReader->addBody("if ((\$id & {$valueGroupIdMask}) > 0) {");
$valueCount = 0;
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\XML\\XmlValue") as $xmlValue) {
/** @var XmlValue $xmlValue */
$groupId = $groups[$xmlValue->group];
$fromXmlReader->addBody("\tif ((\$id & {$groupId}) > 0) {")->addBody("\t\t\$value = self::xmlReadValue(\$xml);")->addBody(Strings::indent($this->assignObjectProperty($xmlValue, $property, "\$value"), 2, "\t"))->addBody("\t}")->addBody("");
++$valueCount;
}
}
if (!$valueCount) {
$fromXmlReader->addBody("\t// @XmlValue not specified");
}
$fromXmlReader->addBody("} else {");
$elementsByName = array();
$endElementsByName = array();
$wrappers = [];
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\XML\\XmlElementWrapper") as $xmlElementWrapper) {
/** @var XmlElementWrapper $xmlElementWrapper */
$groupId = $groups[$xmlElementWrapper->group];
$name = strtolower($xmlElementWrapper->name);
$wrapperId = $xmlElementWrapper->group . ":" . $property->getName();
if (!isset($wrappers[$wrapperId])) {
$wrappers[$wrapperId] = 1 << count($wrappers);
}
if (!isset($elementsByName[$name])) {
$elementsByName[$name] = "";
}
$elementsByName[$name] .= "if ((\$id & {$groupId}) > 0 && \$xml->namespaceURI === " . var_export($xmlElementWrapper->namespace, true) . " && \$depth === 2) {\n";
$elementsByName[$name] .= "\t\$wrapped |= {$wrappers[$wrapperId]};\n";
$elementsByName[$name] .= "}\n";
if (!isset($endElementsByName[$name])) {
$endElementsByName[$name] = "";
}
$endElementsByName[$name] .= "if ((\$id & {$groupId}) > 0 && \$xml->namespaceURI === " . var_export($xmlElementWrapper->namespace, true) . " && \$depth === 2) {\n";
$endElementsByName[$name] .= "\t\$wrapped &= ~{$wrappers[$wrapperId]};\n";
$endElementsByName[$name] .= "}\n";
//.........这里部分代码省略.........
示例4: onGenerate
public function onGenerate(AbstractMetaSpec $spec, MetaSpecMatcher $matcher, Type $type, ClassType $class)
{
$namespace = $class->getNamespace();
// extend base class
$namespace->addUse($type->getName(), null, $typeAlias);
$class->addExtend($type->getName());
$class->addComment("Meta class for \\{$type->getName()}")->addComment("")->addComment("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")->addComment("!!! !!!")->addComment("!!! THIS CLASS HAS BEEN AUTO-GENERATED, DO NOT EDIT !!!")->addComment("!!! !!!")->addComment("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// constructor
$constructor = $class->addMethod("__construct");
$constructor->addComment("Constructor")->addBody("self::\$instance = \$this; // avoids cyclic dependency stack overflow");
if ($type->getConstructor()) {
if ($type->getConstructor()->isPublic()) {
$constructor->setVisibility("public");
} elseif ($type->getConstructor()->isProtected()) {
$constructor->setVisibility("protected");
} elseif ($type->getConstructor()->isPrivate()) {
$constructor->setVisibility("private");
}
} else {
$constructor->setVisibility("private");
}
// implement base interface
$namespace->addUse("Skrz\\Meta\\MetaInterface", null, $metaInterfaceAlias);
$class->addImplement("Skrz\\Meta\\MetaInterface");
// getInstance() method
$instance = $class->addProperty("instance");
$instance->setStatic(true);
$instance->setVisibility("private");
$instance->addComment("@var {$class->getName()}");
$getInstance = $class->addMethod("getInstance");
$getInstance->setStatic(true);
$getInstance->addComment("Returns instance of this meta class")->addComment("")->addComment("@return {$class->getName()}");
$getInstance->addBody("if (self::\$instance === null) {")->addBody("\tnew self(); // self::\$instance assigned in __construct")->addBody("}")->addBody("return self::\$instance;");
// create() method
$create = $class->addMethod("create");
$create->setStatic(true);
$create->addComment("Creates new instance of \\{$type->getName()}")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return {$typeAlias}");
$create->addBody("switch (func_num_args()) {");
$maxArguments = 8;
$constructMethod = $type->getConstructor();
for ($i = 0; $i <= $maxArguments; ++$i) {
$create->addBody("\tcase {$i}:");
if ($constructMethod && $i < $constructMethod->getNumberOfRequiredParameters()) {
$create->addBody("\t\tthrow new \\InvalidArgumentException('At least {$constructMethod->getNumberOfRequiredParameters()} arguments have to be supplied.');");
} else {
$args = array();
for ($j = 0; $j < $i; ++$j) {
$args[] = "func_get_arg({$j})";
}
$create->addBody("\t\treturn new {$typeAlias}(" . implode(", ", $args) . ");");
}
}
$create->addBody("\tdefault:");
$create->addBody("\t\tthrow new \\InvalidArgumentException('More than {$maxArguments} arguments supplied, please be reasonable.');");
$create->addBody("}");
// reset() method
$reset = $class->addMethod("reset");
$reset->setStatic(true);
$reset->addComment("Resets properties of \\{$type->getName()} to default values\n")->addComment("")->addComment("@param {$typeAlias} \$object")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return void");
$reset->addParameter("object");
$reset->addBody("if (!(\$object instanceof {$typeAlias})) {")->addBody("\tthrow new \\InvalidArgumentException('You have to pass object of class {$type->getName()}.');")->addBody("}");
foreach ($type->getProperties() as $property) {
if ($property->hasAnnotation("Skrz\\Meta\\Transient")) {
continue;
}
if ($property->isPrivate()) {
throw new MetaException("Private property '{$type->getName()}::\${$property->getName()}'. " . "Either make the property protected/public if you need to process it, " . "or mark it using @Transient annotation.");
}
$reset->addBody("\$object->{$property->getName()} = " . var_export($property->getDefaultValue(), true) . ";");
}
// hash() method
$hash = $class->addMethod("hash");
$hash->setStatic(true);
$hash->addComment("Computes hash of \\{$type->getName()}")->addComment("")->addComment("@param object \$object")->addComment("@param string|resource \$algoOrCtx")->addComment("@param bool \$raw")->addComment("")->addComment("@return string|void");
$hash->addParameter("object");
$hash->addParameter("algoOrCtx")->setDefaultValue("md5")->setOptional(true);
$hash->addParameter("raw")->setDefaultValue(false)->setOptional(true);
$hash->addBody("if (is_string(\$algoOrCtx)) {")->addBody("\t\$ctx = hash_init(\$algoOrCtx);")->addBody("} else {")->addBody("\t\$ctx = \$algoOrCtx;")->addBody("}")->addBody("");
foreach ($type->getProperties() as $property) {
if ($property->hasAnnotation("Skrz\\Meta\\Transient")) {
continue;
}
if ($property->hasAnnotation("Skrz\\Meta\\Hash")) {
continue;
}
$objectPath = "\$object->{$property->getName()}";
$hash->addBody("if (isset({$objectPath})) {");
$hash->addBody("\thash_update(\$ctx, " . var_export($property->getName(), true) . ");");
$baseType = $property->getType();
$indent = "\t";
$before = "";
$after = "";
for ($i = 0; $baseType instanceof ArrayType; ++$i) {
$arrayType = $baseType;
$baseType = $arrayType->getBaseType();
$before .= "{$indent}foreach ({$objectPath} instanceof \\Traversable ? {$objectPath} : (array){$objectPath} as \$v{$i}) {\n";
$after = "{$indent}}\n" . $after;
$indent .= "\t";
$objectPath = "\$v{$i}";
}
//.........这里部分代码省略.........
示例5: onGenerate
public function onGenerate(AbstractMetaSpec $spec, MetaSpecMatcher $matcher, Type $type, ClassType $class)
{
$ns = $class->getNamespace();
$ns->addUse("Skrz\\Meta\\Protobuf\\ProtobufMetaInterface");
$ns->addUse($type->getName(), null, $typeAlias);
$ns->addUse("Skrz\\Meta\\Protobuf\\Binary", null, $binary);
$ns->addUse("Skrz\\Meta\\Protobuf\\ProtobufException", null, $protobufExceptionAlias);
$class->addImplement("Skrz\\Meta\\Protobuf\\ProtobufMetaInterface");
foreach ($type->getProperties() as $property) {
if ($property->hasAnnotation("Skrz\\Meta\\Transient")) {
continue;
}
/** @var ProtobufField $field */
$field = $property->getAnnotation("Skrz\\Meta\\Protobuf\\ProtobufField");
$class->addConst(strtoupper(trim(preg_replace("/([A-Z])/", "_\$1", $property->getName() . "ProtobufField"), "_")), $field->number);
}
$fromProtobuf = $class->addMethod("fromProtobuf");
$fromProtobuf->setStatic(true);
$fromProtobuf->addParameter("input");
$fromProtobuf->addParameter("object", null)->setOptional(true);
$fromProtobuf->addParameter("start", 0)->setReference(true)->setOptional(true);
$fromProtobuf->addParameter("end", null)->setOptional(true);
$fromProtobuf->addComment("Creates \\{$type->getName()} object from serialized Protocol Buffers message.")->addComment("")->addComment("@param string \$input")->addComment("@param {$typeAlias} \$object")->addComment("@param int \$start")->addComment("@param int \$end")->addComment("")->addComment("@throws \\Exception")->addComment("")->addComment("@return {$typeAlias}");
$fromProtobuf->addBody("if (\$object === null) {")->addBody("\t\$object = new {$typeAlias}();")->addBody("}")->addBody("")->addBody("if (\$end === null) {")->addBody("\t\$end = strlen(\$input);")->addBody("}")->addBody("");
$fromProtobuf->addBody("while (\$start < \$end) {");
$fromProtobuf->addBody("\t\$tag = {$binary}::decodeVarint(\$input, \$start);");
$fromProtobuf->addBody("\t\$wireType = \$tag & 0x7;");
$fromProtobuf->addBody("\t\$number = \$tag >> 3;");
$fromProtobuf->addBody("\tswitch (\$number) {");
foreach ($type->getProperties() as $property) {
if ($property->hasAnnotation("Skrz\\Meta\\Transient")) {
continue;
}
$propertyType = $property->getType();
$baseType = $propertyType;
if ($baseType instanceof ArrayType) {
$baseType = $baseType->getBaseType();
}
/** @var ProtobufField $field */
$field = $property->getAnnotation("Skrz\\Meta\\Protobuf\\ProtobufField");
$fromProtobuf->addBody("\t\tcase {$field->number}:");
if ($field->packed) {
$binaryWireType = WireTypeEnum::toBinaryWireType(WireTypeEnum::STRING);
} else {
$binaryWireType = WireTypeEnum::toBinaryWireType($field->wireType);
}
$fromProtobuf->addBody("\t\t\tif (\$wireType !== {$binaryWireType}) {");
$fromProtobuf->addBody("\t\t\t\tthrow new {$protobufExceptionAlias}('Unexpected wire type ' . \$wireType . ', expected {$binaryWireType}.', \$number);");
$fromProtobuf->addBody("\t\t\t}");
$propertyLhs = "\$object->{$property->getName()}";
if ($propertyType->isArray()) {
$fromProtobuf->addBody("\t\t\tif (!(isset({$propertyLhs}) && is_array({$propertyLhs}))) {");
$fromProtobuf->addBody("\t\t\t\t{$propertyLhs} = array();");
$fromProtobuf->addBody("\t\t\t}");
$propertyLhs .= "[]";
}
if ($field->packed) {
$fromProtobuf->addBody("\t\t\t\$packedLength = {$binary}::decodeVarint(\$input, \$start);")->addBody("\t\t\t\$expectedPacked = \$start + \$packedLength;")->addBody("\t\t\tif (\$expectedPacked > \$end) {")->addBody("\t\t\t\tthrow new {$protobufExceptionAlias}('Not enough data.');")->addBody("\t\t\t}")->addBody("\t\t\twhile (\$start < \$expectedPacked) {");
$indent = "\t\t\t\t";
} else {
$indent = "\t\t\t";
}
switch ($field->wireType) {
case WireTypeEnum::VARINT:
$fromProtobuf->addBody("{$indent}{$propertyLhs} = " . ($baseType instanceof BoolType ? "(bool)" : "") . "{$binary}::decodeVarint(\$input, \$start);");
break;
case WireTypeEnum::ZIGZAG:
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeZigzag(\$input, \$start);");
break;
case WireTypeEnum::FIXED64:
$fromProtobuf->addBody("{$indent}\$expectedStart = \$start + 8;")->addBody("{$indent}if (\$expectedStart > \$end) {")->addBody("{$indent}\tthrow new {$protobufExceptionAlias}('Not enough data.');")->addBody("{$indent}}");
if ($baseType instanceof FloatType) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeDouble(\$input, \$start);");
} elseif ($baseType instanceof IntType && $field->unsigned) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeUint64(\$input, \$start);");
} elseif ($baseType instanceof IntType && !$field->unsigned) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeInt64(\$input, \$start);");
} else {
throw new MetaException("Property {$type->getName()}::\${$property->getName()} has wire type '{$field->wireType}' and base type {$baseType}. " . "'{$field->wireType}' supports only float or int base types.");
}
$fromProtobuf->addBody("{$indent}if (\$start !== \$expectedStart) {")->addBody("{$indent}\tthrow new {$protobufExceptionAlias}('Unexpected start. Expected ' . \$expectedStart . ', got ' . \$start . '.', \$number);")->addBody("{$indent}}");
break;
case WireTypeEnum::FIXED32:
$fromProtobuf->addBody("{$indent}\$expectedStart = \$start + 4;")->addBody("{$indent}if (\$expectedStart > \$end) {")->addBody("{$indent}\tthrow new {$protobufExceptionAlias}('Not enough data.');")->addBody("{$indent}}");
if ($baseType instanceof FloatType) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeFloat(\$input, \$start);");
} elseif ($baseType instanceof IntType && $field->unsigned) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeUint32(\$input, \$start);");
} elseif ($baseType instanceof IntType && !$field->unsigned) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = {$binary}::decodeInt32(\$input, \$start);");
} else {
throw new MetaException("Property {$type->getName()}::\${$property->getName()} has wire type '{$field->wireType}' and base type {$baseType}. " . "'{$field->wireType}' supports only float or int base types.");
}
$fromProtobuf->addBody("{$indent}if (\$start !== \$expectedStart) {")->addBody("{$indent}\tthrow new {$protobufExceptionAlias}('Unexpected start. Expected ' . \$expectedStart . ', got ' . \$start . '.', \$number);")->addBody("{$indent}}");
break;
case WireTypeEnum::STRING:
$fromProtobuf->addBody("{$indent}\$length = {$binary}::decodeVarint(\$input, \$start);")->addBody("{$indent}\$expectedStart = \$start + \$length;")->addBody("{$indent}if (\$expectedStart > \$end) {")->addBody("{$indent}\tthrow new {$protobufExceptionAlias}('Not enough data.');")->addBody("{$indent}}");
if ($baseType instanceof StringType) {
$fromProtobuf->addBody("{$indent}{$propertyLhs} = substr(\$input, \$start, \$length);");
$fromProtobuf->addBody("{$indent}\$start += \$length;");
//.........这里部分代码省略.........
示例6: onGenerate
public function onGenerate(AbstractMetaSpec $spec, MetaSpecMatcher $matcher, Type $type, ClassType $class)
{
$groups = array();
$inputOutputClasses = array($type->getName() => true);
$i = 0;
foreach ($this->defaultGroups as $defaultGroup) {
$groups[$defaultGroup] = 1 << $i++;
}
$ns = $class->getNamespace();
$ns->addUse("Skrz\\Meta\\PHP\\PhpMetaInterface");
$ns->addUse($type->getName(), null, $typeAlias);
$ns->addUse("Skrz\\Meta\\Stack", null, $stackAlias);
$class->addImplement("Skrz\\Meta\\PHP\\PhpMetaInterface");
// get groups
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\PHP\\PhpArrayOffset") as $arrayOffset) {
/** @var PhpArrayOffset $arrayOffset */
if (!isset($groups[$arrayOffset->group])) {
$groups[$arrayOffset->group] = 1 << $i++;
}
}
}
// get discriminator
$discriminatorOffsetMap = array();
$discriminatorClassMap = array();
$discriminatorMetaMap = array();
foreach ($type->getAnnotations("Skrz\\Meta\\PHP\\PhpDiscriminatorOffset") as $discriminatorOffset) {
/** @var PhpDiscriminatorOffset $discriminatorOffset */
if (!isset($groups[$discriminatorOffset->group])) {
$groups[$discriminatorOffset->group] = 1 << $i++;
}
$discriminatorOffsetMap[$groups[$discriminatorOffset->group]] = $discriminatorOffset->offset;
}
foreach ($type->getAnnotations("Skrz\\Meta\\PHP\\PhpDiscriminatorMap") as $discriminatorMap) {
/** @var PhpDiscriminatorMap $discriminatorMap */
if (!isset($groups[$discriminatorMap->group])) {
$groups[$discriminatorMap->group] = 1 << $i++;
}
if (isset($discriminatorMetaMap[$groups[$discriminatorMap->group]])) {
throw new MetaException("More @PhpDiscriminatorMap annotations with same group '{$discriminatorMap->group}'.");
}
$discriminatorClassMap[$groups[$discriminatorMap->group]] = array();
$discriminatorMetaMap[$groups[$discriminatorMap->group]] = array();
$currentClassMap =& $discriminatorClassMap[$groups[$discriminatorMap->group]];
$currentMetaMap =& $discriminatorMetaMap[$groups[$discriminatorMap->group]];
foreach ($discriminatorMap->map as $value => $className) {
$currentClassMap[$value] = $className;
$inputOutputClasses[$className] = true;
$currentMetaMap[$value] = $spec->createMetaClassName(Type::fromString($className));
}
}
// add groups property
$groupsProperty = $class->addProperty("groups");
$groupsProperty->setStatic(true)->setValue($groups)->setVisibility("private");
$groupsProperty->addComment("Mapping from group name to group ID for fromArray() and toArray()")->addComment("")->addComment("@var string[]");
// create input/output type hint
$inputOutputTypeHint = array();
$inputOutputClasses = array_keys($inputOutputClasses);
sort($inputOutputClasses);
foreach ($inputOutputClasses as $inputOutputClass) {
$ns->addUse($inputOutputClass, null, $alias);
$inputOutputTypeHint[] = $alias;
}
$inputOutputTypeHint = implode("|", $inputOutputTypeHint);
foreach (array("Array", "Object") as $what) {
// from*() method
$from = $class->addMethod("from{$what}");
$from->setStatic(true);
$from->addParameter("input");
$from->addParameter("group")->setOptional(true);
$from->addParameter("object")->setOptional(true);
$from->addComment("Creates \\{$type->getName()} object from " . strtolower($what))->addComment("")->addComment("@param " . strtolower($what) . " \$input")->addComment("@param string \$group")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("")->addComment("@throws \\Exception")->addComment("")->addComment("@return {$inputOutputTypeHint}");
if ($what === "Object") {
$from->addBody("\$input = (array)\$input;\n");
}
// TODO: more groups - include/exclude
$from->addBody("if (!isset(self::\$groups[\$group])) {")->addBody("\tthrow new \\InvalidArgumentException('Group \\'' . \$group . '\\' not supported for ' . " . var_export($type->getName(), true) . " . '.');")->addBody("} else {")->addBody("\t\$id = self::\$groups[\$group];")->addBody("}")->addBody("");
if (!empty($discriminatorMetaMap)) {
foreach ($discriminatorMetaMap as $groupId => $groupDiscriminatorMetaMap) {
if (isset($discriminatorOffsetMap[$groupId])) {
$groupDiscriminatorOffset = $discriminatorOffsetMap[$groupId];
foreach ($groupDiscriminatorMetaMap as $value => $metaClass) {
$ns->addUse($metaClass, null, $alias);
$from->addBody("if ((\$id & {$groupId}) > 0 && " . "isset(\$input[" . var_export($groupDiscriminatorOffset, true) . "]) && " . "\$input[" . var_export($groupDiscriminatorOffset, true) . "] === " . var_export($value, true) . ") {")->addBody("\treturn {$alias}::from{$what}(\$input, \$group, \$object);")->addBody("}")->addBody("");
}
} else {
foreach ($groupDiscriminatorMetaMap as $value => $metaClass) {
$ns->addUse($metaClass, null, $alias);
$from->addBody("if ((\$id & {$groupId}) > 0 && " . "isset(\$input[" . var_export($value, true) . "])) {")->addBody("\treturn {$alias}::from{$what}(\$input[" . var_export($value, true) . "], \$group, \$object);")->addBody("}")->addBody("");
}
}
}
}
$from->addBody("if (\$object === null) {")->addBody("\t\$object = new {$typeAlias}();")->addBody("} elseif (!(\$object instanceof {$typeAlias})) {")->addBody("\tthrow new \\InvalidArgumentException('You have to pass object of class {$type->getName()}.');")->addBody("}")->addBody("");
foreach ($type->getProperties() as $property) {
foreach ($property->getAnnotations("Skrz\\Meta\\PHP\\PhpArrayOffset") as $arrayOffset) {
/** @var PhpArrayOffset $arrayOffset */
$groupId = $groups[$arrayOffset->group];
$arrayKey = var_export($arrayOffset->offset, true);
$baseArrayPath = $arrayPath = "\$input[{$arrayKey}]";
//.........这里部分代码省略.........
示例7: onGenerate
public function onGenerate(AbstractMetaSpec $spec, MetaSpecMatcher $matcher, Type $type, ClassType $class)
{
$ns = $class->getNamespace();
$inputOutputClasses = array($type->getName() => true);
foreach ($type->getAnnotations("Skrz\\Meta\\JSON\\JsonDiscriminatorMap") as $discriminatorMap) {
/** @var JsonDiscriminatorMap $discriminatorMap */
foreach ($discriminatorMap->map as $value => $className) {
$inputOutputClasses[$className] = true;
}
}
$inputOutputClasses = array_keys($inputOutputClasses);
sort($inputOutputClasses);
$inputOutputTypeHint = array();
foreach ($inputOutputClasses as $className) {
$ns->addUse($className, null, $alias);
$inputOutputTypeHint[] = $alias;
}
$inputOutputTypeHint = implode("|", $inputOutputTypeHint);
$ns->addUse("Skrz\\Meta\\JSON\\JsonMetaInterface");
$ns->addUse($type->getName(), null, $typeAlias);
$class->addImplement("Skrz\\Meta\\JSON\\JsonMetaInterface");
// fromJson()
$fromJson = $class->addMethod("fromJson");
$fromJson->setStatic(true);
$fromJson->addParameter("json");
$fromJson->addParameter("group")->setOptional(true);
$fromJson->addParameter("object")->setOptional(true);
$fromJson->addComment("Creates \\{$type->getName()} from JSON array / JSON serialized string")->addComment("")->addComment("@param array|string \$json")->addComment("@param string \$group")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return {$inputOutputTypeHint}");
$fromJson->addBody("if (is_array(\$json)) {")->addBody("\t// ok, nothing to do here")->addBody("} elseif (is_string(\$json)) {")->addBody("\t\$decoded = json_decode(\$json, true);")->addBody("\tif (\$decoded === null && \$json !== '' && strcasecmp(\$json, 'null')) {")->addBody("\t\tthrow new \\InvalidArgumentException('Could not decode given JSON: ' . \$json . '.');")->addBody("\t}")->addBody("\t\$json = \$decoded;")->addBody("} else {")->addBody("\tthrow new \\InvalidArgumentException('Expected array, or string, ' . gettype(\$json) . ' given.');")->addBody("}")->addBody("");
$fromJson->addBody("return self::fromObject(\$json, 'json:' . \$group, \$object);");
// toJson()
$toJson = $class->addMethod("toJson");
$toJson->setStatic(true);
$toJson->addParameter("object");
$toJson->addParameter("group")->setOptional(true);
$toJson->addParameter("filterOrOptions")->setOptional(true);
$toJson->addParameter("options", 0)->setOptional(true);
$toJson->addComment("Serializes \\{$type->getName()} to JSON string")->addComment("")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("@param string \$group")->addComment("@param array|int \$filterOrOptions")->addComment("@param int \$options")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return string");
$toJson->addBody("if (is_int(\$filterOrOptions)) {")->addBody("\t\$options = \$filterOrOptions;")->addBody("\t\$filterOrOptions = null;")->addBody("}")->addBody("")->addBody("return json_encode(self::toObject(\$object, 'json:' . \$group, \$filterOrOptions), \$options);");
// toJsonString()
$toJsonString = $class->addMethod("toJsonString");
$toJsonString->setStatic(true);
$toJsonString->addParameter("object");
$toJsonString->addParameter("group")->setOptional(true);
$toJsonString->addComment("Serializes \\{$type->getName()} to JSON string (only for BC, TO BE REMOVED)")->addComment("")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("@param string \$group")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@deprecated")->addComment("")->addComment("@return string");
$toJsonString->addBody("return self::toJson(\$object, \$group);");
// toJsonStringPretty()
$toJsonStringPretty = $class->addMethod("toJsonStringPretty");
$toJsonStringPretty->setStatic(true);
$toJsonStringPretty->addParameter("object");
$toJsonStringPretty->addParameter("group")->setOptional(true);
$toJsonStringPretty->addComment("Serializes \\{$type->getName()} to JSON pretty string (only for BC, TO BE REMOVED)")->addComment("")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("@param string \$group")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@deprecated")->addComment("")->addComment("@return string");
$toJsonStringPretty->addBody("return self::toJson(\$object, \$group, JSON_PRETTY_PRINT);");
// fromArrayOfJson(), toArrayOfJson()
$fromArrayOfJson = $class->addMethod("fromArrayOfJson");
$fromArrayOfJson->setStatic(true);
$fromArrayOfJson->addParameter("input");
$fromArrayOfJson->addParameter("group")->setOptional(true);
$fromArrayOfJson->addParameter("object")->setOptional(true);
$fromArrayOfJson->addComment("Creates \\{$type->getName()} from array of JSON-serialized properties")->addComment("")->addComment("@param array \$input")->addComment("@param string \$group")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("")->addComment("@return {$inputOutputTypeHint}");
$fromArrayOfJson->addBody("\$group = 'json:' . \$group;")->addBody("if (!isset(self::\$groups[\$group])) {")->addBody("\tthrow new \\InvalidArgumentException('Group \\'' . \$group . '\\' not supported for ' . " . var_export($type->getName(), true) . " . '.');")->addBody("} else {")->addBody("\t\$id = self::\$groups[\$group];")->addBody("}")->addBody("");
$toArrayOfJson = $class->addMethod("toArrayOfJson");
$toArrayOfJson->setStatic(true);
$toArrayOfJson->addParameter("object");
$toArrayOfJson->addParameter("group")->setOptional(true);
$toArrayOfJson->addParameter("filterOrOptions", 0)->setOptional(true);
$toArrayOfJson->addParameter("options", 0)->setOptional(true);
$toArrayOfJson->addComment("Transforms \\{$type->getName()} into array of JSON-serialized strings")->addComment("")->addComment("@param {$inputOutputTypeHint} \$object")->addComment("@param string \$group")->addComment("@param array|int \$filterOrOptions")->addComment("@param int \$options")->addComment("")->addComment("@throws \\InvalidArgumentException")->addComment("")->addComment("@return array");
$toArrayOfJson->addBody("if (is_int(\$filterOrOptions)) {")->addBody("\t\$options = \$filterOrOptions;")->addBody("\t\$filter = null;")->addBody("} else {")->addBody("\t\$filter = \$filterOrOptions;")->addBody("}")->addBody("")->addBody("\$group = 'json:' . \$group;")->addBody("if (!isset(self::\$groups[\$group])) {")->addBody("\tthrow new \\InvalidArgumentException('Group \\'' . \$group . '\\' not supported for ' . " . var_export($type->getName(), true) . " . '.');")->addBody("} else {")->addBody("\t\$id = self::\$groups[\$group];")->addBody("}")->addBody("")->addBody("\$output = (array)self::toObject(\$object, \$group, \$filter);")->addBody("");
$groups = $class->getProperty("groups")->value;
foreach ($type->getProperties() as $property) {
if ($property->getType() instanceof ScalarType) {
continue;
// skip scalar fields
}
foreach ($property->getAnnotations("Skrz\\Meta\\JSON\\JsonProperty") as $jsonProperty) {
/** @var JsonProperty $jsonProperty */
$arrayOffset = new PhpArrayOffset();
$arrayOffset->offset = $jsonProperty->name;
$arrayOffset->group = "json:" . $jsonProperty->group;
if ($this->phpModule->getMatchingPropertySerializer($property, $arrayOffset) !== null) {
continue;
// skip custom-serialized fields
}
$groupId = $groups[$arrayOffset->group];
$inputPath = var_export($arrayOffset->offset, true);
$fromArrayOfJson->addBody("if ((\$id & {$groupId}) > 0 && isset(\$input[{$inputPath}]) && is_string(\$input[{$inputPath}])) {")->addBody("\t\$decoded = json_decode(\$input[{$inputPath}], true);")->addBody("\tif (\$decoded === null && \$input[{$inputPath}] !== '' && strcasecmp(\$input[{$inputPath}], 'null')) {")->addBody("\t\tthrow new \\InvalidArgumentException('Could not decode given JSON: ' . \$input[{$inputPath}] . '.');")->addBody("\t}")->addBody("\t\$input[{$inputPath}] = \$decoded;")->addBody("}")->addBody("");
$toArrayOfJson->addBody("if ((\$id & {$groupId}) > 0 && isset(\$output[{$inputPath}]) && (\$filter === null || isset(\$filter[{$inputPath}]))) {")->addBody("\t\$output[{$inputPath}] = json_encode(\$output[{$inputPath}], \$options);")->addBody("}")->addBody("");
}
}
$fromArrayOfJson->addBody("/** @var object \$input */")->addBody("return self::fromObject(\$input, \$group, \$object);");
$toArrayOfJson->addBody("return \$output;");
}