Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configurable namespace root in PHP #460

Merged
merged 23 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .config/ci/php/phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
parameters:
level: 9 # https://phpstan.org/user-guide/rule-levels
paths:
- ../../../generated/Types
- ../../../generated/Runtime
- ../../../generated/php/src

# ignoreErrors:
# - identifier: enum.duplicateValue # most likely a schema problem
ignoreErrors:
- identifier: identical.alwaysFalse # not a big deal, duplicated enum values come from the schema
paths:
- ../../../generated/php/src/Common/ScaleDirection.php
10 changes: 10 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ env:
GO_VERSION: '1.21'
NODE_VERSION: '18'
PYTHON_VERSION: '3.12'
PHP_VERSION: '8.3'
DOCKER_TOOLS: false

jobs:
Expand Down Expand Up @@ -73,6 +74,12 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}

- name: Setup PHP ${{ env.PHP_VERSION }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ env.PHP_VERSION }}
tools: phpstan

- name: Install mypy
run: python3 -m pip install mypy

Expand Down Expand Up @@ -105,6 +112,9 @@ jobs:
- name: Lint generated Python code
run: mypy generated/python/

- name: Lint generated PHP code
run: phpstan analyze --memory-limit 256M -c .config/ci/php/phpstan.neon

examples:
name: Run examples
runs-on: ubuntu-latest
Expand Down
4 changes: 3 additions & 1 deletion config/foundation_sdk.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ parameters:
kind_registry_version: 'v10.4.x'
grafana_version: 'v10.4.x'
go_package_root: 'github.com/grafana/cog/generated'
php_namespace_root: 'Grafana\Foundation'
java_package_path: 'com.grafana.foundation'

inputs:
Expand Down Expand Up @@ -83,7 +84,8 @@ output:
package_root: '%go_package_root%'
- jsonschema: {}
- openapi: {}
- php: {}
- php:
namespace_root: '%php_namespace_root%'
- python:
path_prefix: grafana_foundation_sdk
- typescript: {}
Expand Down
3 changes: 1 addition & 2 deletions examples/php/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
"type": "project",
"autoload": {
"psr-4": {
"Runtime\\": "../../generated/Runtime",
"Types\\": "../../generated/Types"
"Grafana\\Foundation\\": "../../generated/src"
}
},
"require": {}
Expand Down
6 changes: 4 additions & 2 deletions examples/php/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

require_once __DIR__.'/vendor/autoload.php';

echo 'lala';
$dashBuilder = new \Grafana\Foundation\Dashboard\DashboardBuilder(title: "Awesome dashboard");
$dashBuilder->refresh("5m");
$dash = $dashBuilder->build();

$dashboard = new \Types\Dashboard\Dashboard();
var_dump(json_encode($dash));
7 changes: 5 additions & 2 deletions internal/ast/compiler/inline_objects_with_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ func (pass *InlineObjectsWithTypes) Process(schemas []*ast.Schema) ([]*ast.Schem

for _, schema := range schemas {
schema.Objects.Iterate(func(_ string, object ast.Object) {
if !object.Type.IsAnyOf(pass.InlineTypes...) {
// follow potential references
resolvedType := ast.Schemas(schemas).ResolveToType(object.Type)

if !resolvedType.IsAnyOf(pass.InlineTypes...) {
return
}

Expand All @@ -57,7 +60,7 @@ func (pass *InlineObjectsWithTypes) Process(schemas []*ast.Schema) ([]*ast.Schem
return
}

pass.objectsToInline.Set(object.SelfRef.String(), object.Type)
pass.objectsToInline.Set(object.SelfRef.String(), resolvedType)
})
}

Expand Down
13 changes: 13 additions & 0 deletions internal/ast/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ func (schemas Schemas) Locate(pkg string) (*Schema, bool) {
return nil, false
}

func (schemas Schemas) ResolveToType(def Type) Type {
if !def.IsRef() {
return def
}

resolved, found := schemas.LocateObjectByRef(def.AsRef())
if !found {
return def
}

return schemas.ResolveToType(resolved.Type)
}

func (schemas Schemas) LocateObject(pkg string, name string) (Object, bool) {
for _, schema := range schemas {
if schema.Package != pkg {
Expand Down
10 changes: 10 additions & 0 deletions internal/ast/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,16 @@ func (t RefType) DeepCopy() RefType {
}
}

func (t RefType) AsType() Type {
return Type{
Kind: KindRef,
Ref: &RefType{
ReferredPkg: t.ReferredPkg,
ReferredType: t.ReferredType,
},
}
}

type ScalarType struct {
ScalarKind ScalarKind `yaml:"scalar_kind"` // bool, bytes, string, int, float, ...
Value any `json:",omitempty"` // if value isn't nil, we're representing a constant scalar
Expand Down
3 changes: 3 additions & 0 deletions internal/codegen/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ func (outputLanguage *OutputLanguage) interpolateParameters(interpolator Paramet
if outputLanguage.Go != nil {
outputLanguage.Go.InterpolateParameters(interpolator)
}
if outputLanguage.PHP != nil {
outputLanguage.PHP.InterpolateParameters(interpolator)
}
if outputLanguage.Python != nil {
outputLanguage.Python.InterpolateParameters(interpolator)
}
Expand Down
9 changes: 7 additions & 2 deletions internal/jennies/php/add_typehints_comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@ package php
import (
"github.com/grafana/cog/internal/ast"
"github.com/grafana/cog/internal/ast/compiler"
"github.com/grafana/cog/internal/languages"
)

var _ compiler.Pass = (*AddTypehintsComments)(nil)

type AddTypehintsComments struct {
config Config
hinter *typehints
}

func (pass *AddTypehintsComments) Process(schemas []*ast.Schema) ([]*ast.Schema, error) {
pass.hinter = &typehints{}
pass.hinter = &typehints{
config: pass.config,
context: languages.Context{Schemas: schemas},
}

visitor := &compiler.Visitor{
OnStructField: pass.processStructField,
Expand All @@ -26,7 +31,7 @@ func (pass *AddTypehintsComments) processStructField(_ *compiler.Visitor, _ *ast
return field, nil
}

hint := pass.hinter.annotationForType(field.Type)
hint := pass.hinter.varAnnotationForType(field.Type)
if hint != "" {
field.Comments = append(field.Comments, hint)
}
Expand Down
140 changes: 140 additions & 0 deletions internal/jennies/php/builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package php

import (
"fmt"
"path/filepath"
"strings"

"github.com/grafana/codejen"
"github.com/grafana/cog/internal/ast"
"github.com/grafana/cog/internal/languages"
"github.com/grafana/cog/internal/tools"
)

type Builder struct {
config Config
typeFormatter *typeFormatter
}

func (jenny *Builder) JennyName() string {
return "PHPBuilder"
}

func (jenny *Builder) Generate(context languages.Context) (codejen.Files, error) {
var err error
jenny.typeFormatter = builderTypeFormatter(jenny.config, context)

files := make([]codejen.File, 0, len(context.Builders))

// Add argument typehints and ensure arguments are not nullable
hinter := &typehints{config: jenny.config, context: context, resolveBuilders: true}
visitor := ast.BuilderVisitor{
OnOption: func(visitor *ast.BuilderVisitor, schemas ast.Schemas, builder ast.Builder, option ast.Option) (ast.Option, error) {
option.Args = tools.Map(option.Args, func(arg ast.Argument) ast.Argument {
newArg := arg.DeepCopy()
newArg.Type.Nullable = false

if !hinter.requiresHint(newArg.Type) {
return newArg
}

typehint := hinter.paramAnnotationForType(newArg.Name, newArg.Type)
if typehint != "" {
option.Comments = append(option.Comments, typehint)
}

return newArg
})

return option, nil
},
}
context.Builders, err = visitor.Visit(context.Schemas, context.Builders)
if err != nil {
return nil, err
}

for _, builder := range context.Builders {
output, err := jenny.generateBuilder(context, builder)
if err != nil {
return nil, err
}

filename := filepath.Join(
"src",
formatPackageName(builder.Package),
fmt.Sprintf("%sBuilder.php", formatObjectName(builder.Name)),
)
files = append(files, *codejen.NewFile(filename, output, jenny))
}

return files, nil
}

func (jenny *Builder) generateBuilder(context languages.Context, builder ast.Builder) ([]byte, error) {
var buffer strings.Builder

builder.For.Comments = append(
builder.For.Comments,
fmt.Sprintf("@implements %s<%s>", jenny.config.fullNamespaceRef("Cog\\Builder"), jenny.typeFormatter.doFormatType(builder.For.SelfRef.AsType(), false)),
)

hinter := &typehints{config: jenny.config, context: context, resolveBuilders: false}

err := templates.
Funcs(map[string]any{
"fullNamespaceRef": jenny.config.fullNamespaceRef,
"formatPath": jenny.formatFieldPath,
"formatType": jenny.typeFormatter.formatType,
"formatRawType": func(def ast.Type) string {
return jenny.typeFormatter.doFormatType(def, false)
},
"formatRawTypeNotNullable": func(def ast.Type) string {
typeDef := def.DeepCopy()
typeDef.Nullable = false

return jenny.typeFormatter.doFormatType(typeDef, false)
},
"typeHasBuilder": context.ResolveToBuilder,
"isDisjunctionOfBuilders": context.IsDisjunctionOfBuilders,
"typeHint": func(def ast.Type) string {
clone := def.DeepCopy()
clone.Nullable = false

return hinter.forType(clone, false)
},
"resolvesToComposableSlot": func(typeDef ast.Type) bool {
_, found := context.ResolveToComposableSlot(typeDef)
return found
},
"formatValue": func(destinationType ast.Type, value any) string {
if destinationType.IsRef() {
referredObj, found := context.LocateObject(destinationType.AsRef().ReferredPkg, destinationType.AsRef().ReferredType)
if found && referredObj.Type.IsEnum() {
return jenny.typeFormatter.formatEnumValue(referredObj, value)
}
}

return formatValue(value)
},
"defaultForType": func(typeDef ast.Type) string {
return formatValue(defaultValueForType(jenny.config, context.Schemas, typeDef, nil))
},
}).
ExecuteTemplate(&buffer, "builders/builder.tmpl", map[string]any{
"NamespaceRoot": jenny.config.NamespaceRoot,
"Builder": builder,
"ObjectName": jenny.typeFormatter.formatRef(builder.For.SelfRef.AsType(), false),
})
if err != nil {
return nil, err
}

return []byte(buffer.String()), nil
}

func (jenny *Builder) formatFieldPath(fieldPath ast.Path) string {
return strings.Join(tools.Map(fieldPath, func(item ast.PathItem) string {
return formatFieldName(item.Identifier)
}), "->")
}
36 changes: 36 additions & 0 deletions internal/jennies/php/builder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package php

import (
"testing"

"github.com/grafana/cog/internal/languages"
"github.com/grafana/cog/internal/testutils"
"github.com/stretchr/testify/require"
)

func TestBuilder_Generate(t *testing.T) {
test := testutils.GoldenFilesTestSuite[languages.Context]{
TestDataRoot: "../../../testdata/jennies/builders",
Name: "PHPBuilder",
}

config := Config{
NamespaceRoot: "Grafana\\Foundation",
}
language := New(config)
jenny := Builder{config: config}

test.Run(t, func(tc *testutils.Test[languages.Context]) {
var err error
req := require.New(tc)

context := tc.UnmarshalJSONInput(testutils.BuildersContextInputFile)
context, err = languages.GenerateBuilderNilChecks(language, context)
req.NoError(err)

files, err := jenny.Generate(context)
req.NoError(err)

tc.WriteFiles(files)
})
}
Loading
Loading