55
66use Swaggest \GoCodeBuilder \JsonSchema \GoBuilder ;
77use Swaggest \GoCodeBuilder \JsonSchema \TypeBuilder ;
8+ use Swaggest \GoCodeBuilder \Templates \GoFile ;
89use Swaggest \JsonSchema \Context ;
910use Swaggest \JsonSchema \RemoteRef \Preloaded ;
1011use Swaggest \JsonSchema \Schema ;
@@ -449,7 +450,6 @@ public function testTypeNaming()
449450 $ res .= $ generatedStruct ->structDef ->render ();
450451 }
451452
452-
453453 $ this ->assertEquals (<<<'GO'
454454// Another is an enum type.
455455type Another string
@@ -570,4 +570,108 @@ public function testTypeNaming()
570570
571571 }
572572
573+ public function testMissingImport ()
574+ {
575+ $ schemaJson = <<<'JSON'
576+ {
577+ "type": "object",
578+ "$schema": "http://json-schema.org/draft-04/schema#",
579+ "additionalProperties": false,
580+ "properties": {
581+ "version": {
582+ "type": "string"
583+ }
584+ },
585+ "required": [
586+ "version"
587+ ]
588+ }
589+ JSON;
590+ $ schema = Schema::import (json_decode ($ schemaJson ));
591+
592+ $ builder = new GoBuilder ();
593+ $ tb = new TypeBuilder ($ schema , '# ' , $ builder );
594+ $ tb ->build ();
595+
596+ foreach ($ builder ->getGeneratedStructs () as $ generatedStruct ) {
597+ $ builder ->getCode ()->addSnippet ($ generatedStruct ->structDef );
598+ }
599+
600+ $ res = new GoFile ('foo ' );
601+ $ res ->setCode ($ builder ->getCode ());
602+
603+ $ this ->assertEquals (<<<'GO'
604+ // Code generated by github.com/swaggest/go-code-builder, DO NOT EDIT.
605+
606+ package foo
607+
608+ import (
609+ "encoding/json"
610+ "errors"
611+ "fmt"
612+ )
613+
614+ // Untitled1 structure is generated from "#".
615+ type Untitled1 struct {
616+ Version string `json:"version"` // Required.
617+ }
618+
619+ type marshalUntitled1 Untitled1
620+
621+ var knownKeysUntitled1 = []string{
622+ "version",
623+ }
624+
625+ var requireKeysUntitled1 = []string{
626+ "version",
627+ }
628+
629+ // UnmarshalJSON decodes JSON.
630+ func (u *Untitled1) UnmarshalJSON(data []byte) error {
631+ var err error
632+
633+ mu := marshalUntitled1(*u)
634+
635+ err = json.Unmarshal(data, &mu)
636+ if err != nil {
637+ return err
638+ }
639+
640+ var rawMap map[string]json.RawMessage
641+
642+ err = json.Unmarshal(data, &rawMap)
643+ if err != nil {
644+ rawMap = nil
645+ }
646+
647+ for _, key := range requireKeysUntitled1 {
648+ if _, found := rawMap[key]; !found {
649+ return errors.New("required key missing: " + key)
650+ }
651+ }
652+
653+ for _, key := range knownKeysUntitled1 {
654+ delete(rawMap, key)
655+ }
656+
657+ if len(rawMap) != 0 {
658+ offendingKeys := make([]string, 0, len(rawMap))
659+
660+ for key := range rawMap {
661+ offendingKeys = append(offendingKeys, key)
662+ }
663+
664+ return fmt.Errorf("additional properties not allowed in Untitled1: %v", offendingKeys)
665+ }
666+
667+ *u = Untitled1(mu)
668+
669+ return nil
670+ }
671+
672+ GO
673+ , $ res ->render ());
674+
675+ }
676+
573677}
0 commit comments