Skip to content

Conversation

matty0501
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/3049406579/88333?viewId=7627047

Summary

Added new snippet that will populate a Radio field with the next 10 Thursdays, and assign each choice an inventory of 25. It's customizable to use for other days, and includes the ability to set a cutoff day and time for populating the current week's day.

@matty0501 matty0501 requested a review from saifsultanc August 29, 2025 13:45
Copy link

coderabbitai bot commented Aug 29, 2025

Walkthrough

Adds a new Gravity Forms snippet that populates a radio field (form 123, field 1) with the next N weekly dates and per-day inventory, using configurable weekday, cutoff day/time, count, inventory limit, and date format; hooks into pre-render and pre-validation with a one-time-per-page guard.

Changes

Cohort / File(s) Summary of Changes
GF inventory day-population feature
gp-inventory/gpi-populate-days.php
Adds gw_populate_days_into_radio( $form ) and registers hooks (gform_pre_render_123, gform_pre_validation_123) to dynamically populate a radio field with the next N occurrences of a specified weekday, enforce a cutoff rule to skip the current week when applicable, set inventory_limit on each choice, and use a static guard to prevent duplicate runs per page.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant GF as Gravity Forms (Form 123)
  participant Plugin as gw_populate_days_into_radio

  User->>GF: Load form / Submit (pre-render / pre-validation)
  GF->>Plugin: Invoke hook (gform_pre_render_123 / gform_pre_validation_123)
  rect rgb(238,246,255)
    Note over Plugin: static guard ensures single run per page
    Plugin->>Plugin: Determine start date (this <weekday>)
    alt Cutoff applies (weekday/time past cutoff)
      Plugin->>Plugin: Advance start by 1 week (skip this week's date)
    end
    loop generate choices (1..number_of_days)
      Plugin->>Plugin: date_i = start + (i-1) weeks
      Plugin->>Plugin: Build choice {text/value = formatted date, inventory_limit}
    end
    Plugin-->>GF: Return modified form with populated radio choices
  end
  GF-->>User: Render/Validate form with populated choices
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • veryspry

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1e78b4f and 5a3b52a.

📒 Files selected for processing (1)
  • gp-inventory/gpi-populate-days.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • gp-inventory/gpi-populate-days.php
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch matty0501-patch-1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

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: 3

🧹 Nitpick comments (3)
gp-inventory/gpi-populate-days.php (3)

70-76: Cast inventory to int and keep array stable.

Small hardening: ensure an integer limit is set.

-				$label = $start_day->format( $format );
+				$label = $start_day->format( $format );
 				$choices[] = array( 
 					'text' => $label,
-					'value' => $label,
-					'inventory_limit' => $inventory,
+					'value' => $label,
+					'inventory_limit' => (int) $inventory,
 				);

Note: inventory_limit is the correct choice key GP Inventory reads. (gravitywiz.com)


50-55: Scope the “run once” guard by form ID.

Safer if this snippet is expanded to more forms; avoids blocking population for other forms in the same request.

-	static $has_run = false;
-	if ( $has_run ) {
-		return $form;
-	}
-	$has_run = true;
+	static $has_run = array();
+	if ( ! empty( $has_run[ $form['id'] ] ) ) {
+		return $form;
+	}
+	$has_run[ $form['id'] ] = true;

21-23: Hooks look good; consider covering admin and submission paths too.

Pre-render and pre-validation are correct. Optionally add gform_pre_submission_filter_123 and gform_admin_pre_render_123 for parity across AJAX submissions and admin UI.

 add_filter( 'gform_pre_render_123', 'gw_populate_days_into_radio', 5, 1 );
 add_filter( 'gform_pre_validation_123', 'gw_populate_days_into_radio', 5, 1 );
+add_filter( 'gform_pre_submission_filter_123', 'gw_populate_days_into_radio', 5, 1 );
+add_filter( 'gform_admin_pre_render_123', 'gw_populate_days_into_radio', 5, 1 );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 91b6f40 and 107137b.

📒 Files selected for processing (1)
  • gp-inventory/gpi-populate-days.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: PHPCS (Files Changed)
gp-inventory/gpi-populate-days.php

[warning] 73-73:
Array double arrow not aligned correctly; expected 11 space(s) between "'value'" and double arrow, but found 1.


[warning] 72-72:
Array double arrow not aligned correctly; expected 12 space(s) between "'text'" and double arrow, but found 1.


[warning] 70-70:
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 64-64:
Expected 1 space(s) after cast statement; 0 found


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[warning] 60-60:
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 3 spaces


[warning] 59-59:
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space


[failure] 47-47:
Whitespace found at end of line


[failure] 15-15:
Whitespace found at end of line


[failure] 13-13:
Whitespace found at end of line


[failure] 5-5:
Whitespace found at end of line

🪛 GitHub Actions: PHP Lint (PR)
gp-inventory/gpi-populate-days.php

[error] 5-5: PHPCS (step: Run thenabeel/action-phpcs@v8): Whitespace found at end of line (Squiz.WhiteSpace.SuperfluousWhitespace.EndLine).

🔇 Additional comments (2)
gp-inventory/gpi-populate-days.php (2)

56-58: Field targeting and type check are correct.

Good guard; prevents accidental population of other fields.


68-79: Choice generation loop is solid.

Correct count, step, and weekly increment.

Comment on lines 59 to 63
$choices = array();
$today = new DateTime();
$start_day = new DateTime( 'this ' . $day );

// If it's past the cutoff, also skip this week's day
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use the WordPress timezone to avoid server/WP offset drift.

Gravity Forms/WordPress operate in the site timezone; default DateTime() may use server TZ. Initialize with wp_timezone() for consistency.

-			$choices = array();
-			$today   = new DateTime();
-			$start_day = new DateTime( 'this ' . $day );
+			$choices   = array();
+			$tz        = function_exists( 'wp_timezone' ) ? wp_timezone() : null;
+			$today     = new DateTime( 'now', $tz );
+			$start_day = new DateTime( 'this ' . $day, $tz );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$choices = array();
$today = new DateTime();
$start_day = new DateTime( 'this ' . $day );
// If it's past the cutoff, also skip this week's day
$choices = array();
$tz = function_exists( 'wp_timezone' ) ? wp_timezone() : null;
$today = new DateTime( 'now', $tz );
$start_day = new DateTime( 'this ' . $day, $tz );
// If it's past the cutoff, also skip this week's day
🧰 Tools
🪛 GitHub Check: PHPCS (Files Changed)

[warning] 60-60:
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 3 spaces


[warning] 59-59:
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

🤖 Prompt for AI Agents
In gp-inventory/gpi-populate-days.php around lines 59 to 63, the DateTime
instances are created without specifying the WordPress timezone causing
potential server vs WP timezone drift; change the DateTime creation to use
wp_timezone() so both $today and $start_day are initialized with the site
timezone (i.e., construct them using the WordPress timezone object returned by
wp_timezone()) to ensure consistent date calculations.

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

♻️ Duplicate comments (3)
gp-inventory/gpi-populate-days.php (3)

63-67: Fix cutoff logic, block past-date inclusion, and satisfy PHPCS on Line 64.

Current condition can surface a past day and fails PHPCS. Replace with guarded, readable logic.

-			// If it's past the cutoff, also skip this week's day
-			if ( ( $today->format('N') == $cutoff_day && ( int )$today->format('H') >= $cutoff_time ) || $today->format('N') > $cutoff_day && $today->format('N') <= $start_day->format('N') ) {
-				$start_day->modify('+1 week');
-			}
+			// Ensure start day is not in the past; then apply cutoff.
+			$midnight   = ( clone $today )->setTime( 0, 0, 0 );
+			if ( $start_day < $midnight ) {
+				$start_day->modify( 'next ' . $day );
+			} else {
+				$today_dow  = (int) $today->format( 'N' );
+				$today_hour = (int) $today->format( 'H' );
+				$target_dow = (int) $start_day->format( 'N' );
+				if (
+					( $today_dow === (int) $cutoff_day && $today_hour >= (int) $cutoff_time )
+					|| ( $today_dow > (int) $cutoff_day && $today_dow <= $target_dow )
+				) {
+					$start_day->modify( '+1 week' );
+				}
+			}

59-63: Initialize dates with the WordPress timezone.

Prevents server/WP offset drift; also improves determinism around cutoff.

-			$choices   = array();
-			$today     = new DateTime();
-			$start_day = new DateTime( 'this ' . $day );
+			$choices   = array();
+			$tz        = function_exists( 'wp_timezone' ) ? wp_timezone() : null;
+			$today     = new DateTime( 'now', $tz );
+			$start_day = new DateTime( 'this ' . $day, $tz );

5-5: Remove trailing whitespace to unblock PHPCS.

These lines still flag Squiz.WhiteSpace.SuperfluousWhitespace.EndLine.

- * 
+ *
- * 
+ *
- * 
+ *
-	// That's it, stop editing!
+	// That's it, stop editing!

Also applies to: 13-13, 15-15, 47-47

🧹 Nitpick comments (2)
gp-inventory/gpi-populate-days.php (2)

57-58: Tighten comparisons and follow WP style.

Use strict compare and Yoda for the string compare.

-		if ( $field->id == $field_id && $field->type == 'radio' ) {
+		if ( (int) $field->id === (int) $field_id && 'radio' === $field->type ) {

69-77: Remove trailing whitespace and apply spacing/cast adjustments

  • Remove trailing space on line 71 after array(
  • Align assignments:
    • $label = $start_day->format( $format );
    • $choices[] = array(
  • Cast inventory: 'inventory_limit' => (int) $inventory,
  • Add spaces in method call: $start_day->modify( '+1 week' );
  • Ensure PHPCS is configured with the PHPCompatibilityWP sniff to verify style compliance
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 107137b and 2394f5c.

📒 Files selected for processing (1)
  • gp-inventory/gpi-populate-days.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: PHPCS (Files Changed)
gp-inventory/gpi-populate-days.php

[warning] 70-70:
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 64-64:
Cast statements must not contain whitespace; expected "(int)" but found "( int )"


[failure] 64-64:
Expected 1 space(s) after cast statement; 0 found


[failure] 64-64:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 64-64:
Expected 1 spaces after opening parenthesis; 0 found

🪛 GitHub Actions: PHP Lint (PR)
gp-inventory/gpi-populate-days.php

[error] 64-64: PHPCS: PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket - Expected 1 spaces after opening parenthesis; 0 found.

🔇 Additional comments (1)
gp-inventory/gpi-populate-days.php (1)

50-55: Idempotency guard looks good.

Prevents double-population across pre-render and pre-validation.

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: 1

♻️ Duplicate comments (2)
gp-inventory/gpi-populate-days.php (2)

63-66: Fix cutoff logic (prevents past-date inclusion) and satisfy PHPCS.

On Fri–Sun, this thursday can be in the past and still be included. Replace the block to guard against past dates and keep the cutoff behavior; also conforms to spacing rules.

-			// If it's past the cutoff, also skip this week's day
-			if ( ( $today->format( 'N' ) == $cutoff_day && ( int )$today->format( 'H' ) >= $cutoff_time ) || $today->format( 'N' ) > $cutoff_day && $today->format( 'N' ) <= $start_day->format( 'N' ) ) {
-				$start_day->modify( '+1 week' );
-			}
+			// If the target day this week has already passed, skip to next week first.
+			$midnight = ( clone $today )->setTime( 0, 0, 0 );
+			if ( $start_day < $midnight ) {
+				$start_day->modify( 'next ' . $day );
+			} else {
+				// If it's past the cutoff, also skip this week's day.
+				$today_dow  = (int) $today->format( 'N' );
+				$target_dow = (int) $start_day->format( 'N' );
+				if (
+					( $today_dow === (int) $cutoff_day && (int) $today->format( 'H' ) >= (int) $cutoff_time )
+					|| ( $today_dow > (int) $cutoff_day && $today_dow <= $target_dow )
+				) {
+					$start_day->modify( '+1 week' );
+				}
+			}

59-62: Use WordPress timezone to avoid server/WP drift.

Initialize DateTime with wp_timezone(); fall back to site TZ or UTC.

-			$choices   = array();
-			$today     = new DateTime();
-			$start_day = new DateTime( 'this ' . $day );
+			$choices   = array();
+			$tz        = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( get_option( 'timezone_string' ) ?: 'UTC' );
+			$today     = new DateTime( 'now', $tz );
+			$start_day = new DateTime( 'this ' . $day, $tz );
🧹 Nitpick comments (2)
gp-inventory/gpi-populate-days.php (2)

71-75: Ensure inventory is an integer.

Cast to int to avoid accidental strings.

-					'inventory_limit' => $inventory,
+					'inventory_limit' => (int) $inventory,

68-75: Optional: Localize date labels.

Use wp_date() for i18n while keeping DateTime for calculations.

-				$label     = $start_day->format( $format );
+				$label     = function_exists( 'wp_date' ) ? wp_date( $format, $start_day->getTimestamp() ) : $start_day->format( $format );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2394f5c and 1e78b4f.

📒 Files selected for processing (1)
  • gp-inventory/gpi-populate-days.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: PHPCS (Files Changed)
gp-inventory/gpi-populate-days.php

[failure] 76-76:
Expected 1 spaces before closing parenthesis; 0 found


[failure] 76-76:
Expected 1 spaces after opening parenthesis; 0 found


[failure] 71-71:
Whitespace found at end of line


[failure] 64-64:
Cast statements must not contain whitespace; expected "(int)" but found "( int )"


[failure] 64-64:
Expected 1 space(s) after cast statement; 0 found

🪛 GitHub Actions: PHP Lint (PR)
gp-inventory/gpi-populate-days.php

[error] 64-64: PHPCS (thenabeel/action-phpcs@v8): Expected 1 space(s) after cast statement; 0 found. (Generic.Formatting.SpaceAfterCast.NoSpace)

🔇 Additional comments (2)
gp-inventory/gpi-populate-days.php (2)

50-55: One-time guard looks good.

Prevents double-population across multiple hooks in a single request.


21-23: Hook setup is appropriate.

ID-specific pre-render and pre-validation filters are correctly targeted.

@saifsultanc saifsultanc merged commit 084abdc into master Aug 29, 2025
4 checks passed
@saifsultanc saifsultanc deleted the matty0501-patch-1 branch August 29, 2025 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants