Skip to content

Commit

Permalink
new inspection for string nullability
Browse files Browse the repository at this point in the history
  • Loading branch information
Hidanio committed Aug 8, 2024
1 parent 326d6be commit 8ff9869
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/linter/quickfix.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ func (g *QuickFixGenerator) NullForNotNullableProperty(prop *ir.PropertyStmt) qu
}
}

func (g *QuickFixGenerator) NullableStringType(param *ir.Name) quickfix.TextEdit {
return quickfix.TextEdit{
StartPos: param.Position.StartPos,
EndPos: param.Position.EndPos,
Replacement: "?string",
}
}

func (g *QuickFixGenerator) GetType(node ir.Node, isFunctionName, nodeText string, isNegative bool) quickfix.TextEdit {
pos := ir.GetPosition(node)

Expand Down
9 changes: 9 additions & 0 deletions src/linter/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ func addBuiltinCheckers(reg *CheckersRegistry) {
After: `$s = strip_tags($s, '<br>')`,
},

{
Name: "nullableString",
Default: true,
Quickfix: true,
Comment: "Report not nullable string can be null.",
Before: `function f(string $str = null);`,
After: `function f(?string $str = null);`,
},

{
Name: "emptyStmt",
Default: true,
Expand Down
18 changes: 17 additions & 1 deletion src/linter/root_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,24 @@ func (r *rootChecker) checkFuncParam(p *ir.Parameter) {
}
return true
})

r.CheckTypeHintFunctionParam(p)
r.CheckParamStringNullability(p)
}

func (r *rootChecker) CheckParamStringNullability(p *ir.Parameter) {
if param, ok := p.VariableType.(*ir.Name); ok {
if param.Value != "string" {
return
}

if defValue, ok := p.DefaultValue.(*ir.ConstFetchExpr); ok {
if defValue.Constant.Value != "null" {
return
}
r.walker.Report(param, LevelWarning, "nullableString", "string with null default value should be explicitly nullable")
r.walker.addQuickFix("nullableString", r.quickfix.NullableStringType(param))
}
}
}

func (r *rootChecker) CheckTypeHintFunctionParam(p *ir.Parameter) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

function f(?string $filed = null) {
return 1;
}
5 changes: 5 additions & 0 deletions src/tests/golden/testdata/quickfix/stringNullable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

function f(string $filed = null) {
return 1;
}

0 comments on commit 8ff9869

Please sign in to comment.