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

feat: better phpstan support part2 #237

Merged
merged 4 commits into from
Nov 6, 2024
Merged

Conversation

taka-oyama
Copy link
Collaborator

@taka-oyama taka-oyama commented Nov 5, 2024

Part1 #236 needs to be merged first.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced ColumnDefinition and RowDeletionPolicyDefinition classes to enhance database schema definitions.
  • Bug Fixes

    • Removed specific error ignore patterns related to the Illuminate\Support\Fluent class, improving error reporting accuracy.
  • Refactor

    • Updated method signatures in the Grammar class to improve type safety and clarity regarding expected parameters.

@taka-oyama taka-oyama added enhancement New feature or request waiting for review labels Nov 5, 2024
@taka-oyama taka-oyama requested a review from a team November 5, 2024 10:32
@taka-oyama taka-oyama self-assigned this Nov 5, 2024
Copy link

coderabbitai bot commented Nov 5, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces several changes across multiple files, primarily focusing on enhancing type safety and clarity in method signatures within the Grammar class and adding new classes for column and row deletion policy definitions. The phpstan.neon configuration file is updated to remove specific error ignore patterns for the Illuminate\Support\Fluent class. New classes ColumnDefinition and RowDeletionPolicyDefinition are created, encapsulating properties relevant to database schema definitions.

Changes

File Change Summary
phpstan.neon Removed error ignore patterns for accessing undefined properties and methods in Illuminate\Support\Fluent.
src/Schema/ColumnDefinition.php Added ColumnDefinition class extending BaseColumnDefinition, with properties for database column characteristics.
src/Schema/Grammar.php Updated method signatures to specify more precise types for $command parameters, enhancing type safety.
src/Schema/RowDeletionPolicyDefinition.php Added RowDeletionPolicyDefinition class extending Fluent, with properties for row deletion policy details.

Possibly related PRs

  • feat: better phpstan support part2 #237: This PR directly relates to the main PR as it also removes the same error ignore patterns associated with the Illuminate\Support\Fluent class in the phpstan.neon configuration file.

Suggested reviewers

  • dkkoma

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@@ -371,6 +371,7 @@ protected function addInterleaveToTable(Blueprint $blueprint)
protected function addRowDeletionPolicy(Blueprint $blueprint)
{
if (! is_null($command = $this->getCommandByName($blueprint, 'rowDeletionPolicy'))) {
/** @var RowDeletionPolicyDefinition $command */
Copy link
Collaborator Author

@taka-oyama taka-oyama Nov 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should use assert but that will break compatibility so it will be done in a later version

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
src/Schema/RowDeletionPolicyDefinition.php (1)

25-33: Consider enhancing type safety with policy constants and validation.

While the current implementation is functional, consider these improvements for better type safety and developer experience:

  1. Add constants for valid policy values to prevent magic strings
  2. Add constructor validation for the properties

Here's a suggested implementation:

 /**
  * @property string $column
  * @property string $policy
  * @property int $days
  * @extends Fluent<string, mixed>
  */
 class RowDeletionPolicyDefinition extends Fluent
 {
+    public const POLICY_DELETE = 'DELETE';
+    // Add other valid policy constants here
+
+    /**
+     * @param array<string, mixed> $attributes
+     */
+    public function __construct(array $attributes = [])
+    {
+        parent::__construct($attributes);
+
+        if (!isset($this->column)) {
+            throw new \InvalidArgumentException('Column must be specified');
+        }
+        if (!isset($this->policy)) {
+            throw new \InvalidArgumentException('Policy must be specified');
+        }
+        if (!isset($this->days) || $this->days <= 0) {
+            throw new \InvalidArgumentException('Days must be a positive integer');
+        }
+        if (!in_array($this->policy, [self::POLICY_DELETE], true)) {
+            throw new \InvalidArgumentException('Invalid policy value');
+        }
+    }
 }
src/Schema/ColumnDefinition.php (1)

25-41: Consider adding method-level type hints.

While the property-level PHPDoc annotations are excellent for static analysis, consider whether any methods need to be added with proper type hints to further enhance type safety. The empty class extension pattern is valid, but documenting why we're not adding any additional functionality would improve maintainability.

Add a class-level PHPDoc comment explaining the purpose:

 /**
+ * Extends the base column definition to provide strict typing information
+ * for Cloud Spanner specific column properties.
+ *
  * @property string $name
  * @property string $type
  * @property string|null $arrayType
src/Schema/Grammar.php (2)

Line range hint 541-733: Consider using an abstract method pattern for type definitions.

While the type hints improve type safety, the repetitive pattern across type methods suggests an opportunity for better abstraction. Consider introducing an abstract method pattern or strategy pattern to handle different column types more elegantly.

Example implementation:

+interface ColumnTypeHandler {
+    public function getTypeDefinition(ColumnDefinition $column): string;
+}

+class StringColumnTypeHandler implements ColumnTypeHandler {
+    public function getTypeDefinition(ColumnDefinition $column): string {
+        return "string({$column->length})";
+    }
+}

 class Grammar extends BaseGrammar {
+    private array $typeHandlers = [];
+
+    public function __construct() {
+        $this->typeHandlers['string'] = new StringColumnTypeHandler();
+        // Add other handlers
+    }
+
+    protected function getColumnType(string $type, ColumnDefinition $column): string {
+        return $this->typeHandlers[$type]->getTypeDefinition($column);
+    }

Line range hint 897-904: Add proper string escaping for default values.

The formatStringValue method doesn't escape special characters in string values, which could lead to SQL injection or syntax errors if the string contains quotes.

Apply this fix:

     protected function formatStringValue(Fluent $column, mixed $value): string
     {
         assert(is_string($value));
-        return '"' . $value . '"';
+        return '"' . str_replace('"', '\"', $value) . '"';
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 04fb5bc and e2c93f8.

📒 Files selected for processing (4)
  • phpstan.neon (0 hunks)
  • src/Schema/ColumnDefinition.php (1 hunks)
  • src/Schema/Grammar.php (36 hunks)
  • src/Schema/RowDeletionPolicyDefinition.php (1 hunks)
💤 Files with no reviewable changes (1)
  • phpstan.neon
🔇 Additional comments (4)
src/Schema/RowDeletionPolicyDefinition.php (1)

1-24: LGTM! File structure follows best practices.

The file includes proper licensing, strict type declarations, and follows PSR-4 autoloading standards.

src/Schema/ColumnDefinition.php (2)

19-21: LGTM! Good use of strict typing.

The strict typing declaration and namespace are correctly defined, which aligns well with the PR's objective of improving PHPStan support.


26-37: Verify property types against Cloud Spanner's constraints.

Let's verify that the property types align with Cloud Spanner's constraints and supported features.

✅ Verification successful

Based on the examination of the Grammar.php file and other results, I can now provide a definitive response about the property types alignment with Cloud Spanner's constraints.

Property types are correctly aligned with Cloud Spanner's data type system

The property types in ColumnDefinition.php perfectly match Cloud Spanner's supported data types and constraints:

  • string: Maps to STRING(n) or STRING(MAX)
  • arrayType: Supports Cloud Spanner's ARRAY type with proper inner type handling
  • nullable: Matches Spanner's NULL/NOT NULL constraint support
  • default: Properly handles all Spanner's supported default values
  • length: Used for STRING(n) and BYTES(n) specifications
  • precision/scale: Used for NUMERIC type
  • useCurrent: Properly implemented for TIMESTAMP columns
  • virtualAs/storedAs: Matches Spanner's computed column support

The implementation in Grammar.php shows proper type mapping and constraint handling for all these properties, with correct SQL generation for Cloud Spanner's syntax.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for Cloud Spanner column type definitions and constraints
# in the codebase to verify alignment with the property types.

# Test: Look for column type definitions
rg -l "column.*type" --type php

# Test: Look for Cloud Spanner specific type constraints
rg -l "spanner.*constraint" --type php

Length of output: 97


Script:

#!/bin/bash
# Let's examine the actual column type implementations and constraints

# Check for Cloud Spanner specific type definitions
rg "Cloud.*Spanner.*type" --type php -A 5

# Look for type mapping or type conversion logic
rg "protected\s+function\s+type" --type php -A 10

# Check Grammar.php for type definitions since it was found in previous search
cat src/Schema/Grammar.php

# Look for any Spanner-specific column definitions
rg "spanner.*column" --type php -i

Length of output: 38691

src/Schema/Grammar.php (1)

Line range hint 171-201: LGTM! Row deletion policy implementation looks solid.

The type hints and assertions for RowDeletionPolicyDefinition improve type safety while maintaining proper error handling for unknown policies.

Also applies to: 374-380

@taka-oyama taka-oyama changed the base branch from master to feature/phpstan-support-part1 November 5, 2024 10:48
@taka-oyama taka-oyama force-pushed the feature/phpstan-support-part2 branch from e9da42e to 0e8c1f0 Compare November 6, 2024 05:48
@taka-oyama taka-oyama mentioned this pull request Nov 6, 2024
15 tasks
Base automatically changed from feature/phpstan-support-part1 to master November 6, 2024 10:42
@taka-oyama taka-oyama merged commit 9cf0e3c into master Nov 6, 2024
1 check passed
@taka-oyama taka-oyama deleted the feature/phpstan-support-part2 branch November 6, 2024 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request waiting for review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants