github.com/googleapis/api-linter@v1.65.2/rules/aip0191/php_namespace.go (about) 1 // Copyright 2019 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package aip0191 16 17 import ( 18 "fmt" 19 "regexp" 20 "strings" 21 22 "github.com/googleapis/api-linter/lint" 23 "github.com/googleapis/api-linter/locations" 24 "github.com/jhump/protoreflect/desc" 25 "github.com/stoewer/go-strcase" 26 ) 27 28 var phpNamespace = &lint.FileRule{ 29 Name: lint.NewRuleName(191, "php-namespace"), 30 OnlyIf: func(f *desc.FileDescriptor) bool { 31 fops := f.GetFileOptions() 32 return fops != nil && fops.GetPhpNamespace() != "" 33 }, 34 LintFile: func(f *desc.FileDescriptor) []lint.Problem { 35 ns := f.GetFileOptions().GetPhpNamespace() 36 delim := `\` 37 38 // Check for invalid characters. 39 if !phpValidChars.MatchString(ns) { 40 return []lint.Problem{{ 41 Message: `Invalid characters: PHP namespaces only allow [A-Za-z0-9\].`, 42 Descriptor: f, 43 Location: locations.FilePhpNamespace(f), 44 }} 45 } 46 47 // Check that upper camel case is used. 48 upperCamel := []string{} 49 for _, segment := range strings.Split(ns, delim) { 50 upperCamel = append(upperCamel, strcase.UpperCamelCase(segment)) 51 } 52 if want := strings.Join(upperCamel, delim); ns != want { 53 return []lint.Problem{{ 54 Message: "PHP namespaces use UpperCamelCase.", 55 Suggestion: fmt.Sprintf( 56 "option php_namespace = %s;", 57 // Even though the string value is a single backslash, we want 58 // to suggest two backslashes, because that is what should be 59 // typed into the editor. We use %s to avoid additional escaping 60 // of backslashes by Sprintf. 61 strings.ReplaceAll(want, delim, `\\`), 62 ), 63 Descriptor: f, 64 Location: locations.FilePhpNamespace(f), 65 }} 66 } 67 68 for _, s := range f.GetServices() { 69 n := s.GetName() 70 if !packagingServiceNameEquals(n, ns, delim) { 71 msg := fmt.Sprintf("Case of PHP namespace and service name %q must match.", n) 72 return []lint.Problem{{ 73 Message: msg, 74 Descriptor: f, 75 Location: locations.FilePhpNamespace(f), 76 }} 77 } 78 } 79 80 return nil 81 }, 82 } 83 84 var phpValidChars = regexp.MustCompile(`^[A-Za-z0-9\\]+$`)