Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Polyfill Ctype Laravel Package

symfony/polyfill-ctype

Symfony Polyfill for Ctype: provides ctype_* functions when the PHP ctype extension isn’t available. Useful for consistent character-type checks across environments and PHP versions. Part of the Symfony Polyfill suite, MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer in your Laravel project:

    composer require symfony/polyfill-ctype
    

    No additional configuration is required—it works as a drop-in replacement.

  2. First Use Case: Replace any ctype_* function calls in your code. For example:

    // Before (may fail if ctype extension is missing)
    if (ctype_alnum($input)) {
        // Process alphanumeric input
    }
    
    // After (works universally)
    if (\ctype_alnum($input)) {  // Note: Use fully qualified namespace
        // Process alphanumeric input
    }
    
  3. Where to Look First:

    • Laravel Validation: Use in FormRequest validation rules or custom validation logic:
      public function rules()
      {
          return [
              'username' => 'required|string|max:255|ctype_alnum',
          ];
      }
      
    • Middleware: Sanitize input in middleware:
      public function handle($request, Closure $next)
      {
          if (\ctype_alpha($request->input('param'))) {
              // Proceed
          }
          return $next($request);
      }
      
    • Custom Logic: Replace manual checks (e.g., preg_match) with ctype_* for readability:
      // Replace:
      if (preg_match('/^[a-zA-Z0-9]+$/', $input)) { ... }
      
      // With:
      if (\ctype_alnum($input)) { ... }
      

Implementation Patterns

Usage Patterns

  1. Validation Layer Integration:

    • FormRequests: Use ctype_* in custom validation rules:
      use Illuminate\Validation\Rule;
      
      public function rules()
      {
          return [
              'slug' => [
                  'required',
                  'string',
                  Rule::custom(function ($attribute, $value) {
                      return \ctype_alnum($value);
                  }),
              ],
          ];
      }
      
    • Custom Rules: Extend Laravel’s FormRequest or create a reusable rule:
      namespace App\Rules;
      
      use Illuminate\Contracts\Validation\Rule as ValidationRule;
      
      class Alphanumeric implements ValidationRule
      {
          public function passes($attribute, $value)
          {
              return \ctype_alnum($value);
          }
      
          public function message()
          {
              return 'The :attribute must be alphanumeric.';
          }
      }
      
      Usage:
      'field' => ['required', new \App\Rules\Alphanumeric],
      
  2. Middleware for Input Sanitization:

    • Sanitize input before processing (e.g., API keys, usernames):
      public function handle($request, Closure $next)
      {
          $input = $request->input('api_key');
          if (!\ctype_alnum(str_replace('-', '', $input))) {
              abort(400, 'Invalid API key format.');
          }
          return $next($request);
      }
      
  3. Slug Generation:

    • Generate SEO-friendly slugs with ctype_* checks:
      public function generateSlug($title)
      {
          $slug = Str::slug($title);
          if (\ctype_alnum($slug)) {
              return $slug;
          }
          return preg_replace('/[^a-zA-Z0-9]+/', '-', $slug);
      }
      
  4. API Input Validation:

    • Validate API payloads in App\Exceptions\Handler or middleware:
      public function validateApiInput($request)
      {
          $data = json_decode($request->getContent(), true);
          foreach ($data as $key => $value) {
              if (\ctype_digit($value) && strlen($value) > 10) {
                  throw new \Exception("Invalid $key format.");
              }
          }
      }
      
  5. Database Constraints:

    • Use ctype_* to validate model attributes before saving:
      public function save(array $options = [])
      {
          if (!\ctype_alnum($this->attributes['username'])) {
              throw new \InvalidArgumentException('Username must be alphanumeric.');
          }
          return parent::save($options);
      }
      

Workflows

  1. Shared Hosting Compatibility:

    • Problem: Deploying to shared hosting (e.g., GoDaddy) where ctype extension is disabled.
    • Solution: Add the polyfill to composer.json and redeploy. No code changes needed.
    • Workflow:
      composer require symfony/polyfill-ctype
      git add composer.json composer.lock
      git commit -m "Add ctype polyfill for shared hosting compatibility"
      git push
      
  2. PHP 8.1+ Migration:

    • Problem: E_DEPRECATED warnings for ctype_* in PHP 8.1+.
    • Solution: Install the polyfill to suppress warnings and maintain compatibility.
    • Workflow:
      composer require symfony/polyfill-ctype
      # Optionally suppress deprecation warnings in bootstrap/app.php:
      error_reporting(E_ALL & ~E_DEPRECATED);
      
  3. CI/CD Pipeline:

    • Problem: Tests fail on CI due to missing ctype extension.
    • Solution: Add the polyfill to composer.json and ensure it’s included in all environments.
    • Workflow:
      # .github/workflows/tests.yml
      jobs:
        test:
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: composer require symfony/polyfill-ctype --dev --no-update
            - run: composer update
            - run: php artisan test
      
  4. Performance Optimization:

    • Problem: Polyfill overhead in high-traffic APIs.
    • Solution: Use native ctype_* where possible and fall back to polyfill.
    • Workflow:
      if (function_exists('ctype_alnum')) {
          // Use native function (faster)
          $isValid = ctype_alnum($input);
      } else {
          // Fall back to polyfill
          $isValid = \ctype_alnum($input);
      }
      

Integration Tips

  1. Laravel Validation Rules:

    • Extend Laravel’s validation with ctype_* checks:
      'username' => 'required|string|max:255|ctype_alnum',
      
    • For complex rules, use custom validation classes (as shown above).
  2. Testing:

    • Mock ctype_* functions in PHPUnit tests to avoid environment dependencies:
      use Symfony\Component\Polyfill\Ctype\Ctype;
      
      beforeEach(function () {
          $this->mockCtype = $this->mock(Ctype::class);
          $this->mockCtype->shouldReceive('alnum')->andReturnTrue();
      });
      
  3. Unicode Handling:

    • Combine with mbstring functions for Unicode support:
      if (\mb_ctype_alnum($input, 'UTF-8')) {
          // Handle Unicode alphanumeric input
      }
      
  4. Legacy Code:

    • Replace custom regex checks with ctype_* for consistency:
      // Before:
      if (preg_match('/^[a-zA-Z]+$/', $input)) { ... }
      
      // After:
      if (\ctype_alpha($input)) { ... }
      
  5. Documentation:

    • Note in your project’s README or CONTRIBUTING.md that ctype_* functions are polyfilled for cross-environment compatibility.

Gotchas and Tips

Pitfalls

  1. Namespace Collisions:

    • Issue: If you use use function ctype_alnum; or use function \ctype_alnum;, the polyfill may not be loaded due to namespace resolution.
    • Fix: Always use the fully qualified namespace:
      \ctype_alnum($input);  // Correct
      ctype_alnum($input);   // May fail if native function exists
      
  2. PHP 8.1+ Deprecation Warnings:

    • Issue: The polyfill suppresses deprecation warnings but may still log them if error_reporting is not configured.
    • Fix: Add this to bootstrap/app.php:
      error_reporting(E_ALL & ~E_DEPRECATED);
      
    • Alternative: Replace ctype_* with Str::isAlphanumeric() or preg_match in critical paths.
  3. Unicode Limitations:

    • Issue: ctype_* functions only support ASCII. For Unicode (e.g., café), use mb_ctype_* or Str::isAlphanumeric().
    • Fix:
      if (\mb_ctype_alnum($input, 'UTF-8')) { ... }
      // Or:
      if (Str::isAlphanumeric($input)) { ... }
      
  4. Performance Overhead:

    • Issue: Polyfilled functions are ~2–
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/graphviz
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata