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

Disallowed Character Terminated String Laravel Package

webignition/disallowed-character-terminated-string

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require webignition/disallowed-character-terminated-string
    
  2. Basic Usage: Import the TerminatedString class and instantiate it with a string and terminator characters:

    use webignition\DisallowedCharacterTerminatedString\TerminatedString;
    
    $string = new TerminatedString("value #comment", ['#']);
    $result = $string->get(); // Returns "value "
    
  3. First Use Case:

    • Stripping Comments: Remove trailing comments from SQL queries or config files.
      $query = "UPDATE users SET name = 'John' # Old value";
      $cleanQuery = (new TerminatedString($query, ['#']))->get();
      
    • Log Processing: Truncate log lines at line breaks or timestamps.
      $logLine = "Error: File not found 2023-10-01 12:00:00";
      $logMessage = (new TerminatedString($logLine, [' ']))->get(); // Truncate at last space
      
  4. Where to Look Next:

    • Class Methods: Explore TerminatedString::get() and constructor parameters.
    • Tests: Review /tests/ for edge cases (e.g., empty strings, no terminators).
    • Laravel Integration: Check how to wrap this in a helper or service.

Implementation Patterns

Core Workflows

  1. String Truncation:

    • Pass a string and an array of terminator characters to the constructor.
    • Call get() to retrieve the truncated string.
    $terminated = new TerminatedString($input, [';', '#']);
    $output = $terminated->get();
    
  2. Laravel Helper Integration: Create a reusable helper method in app/Helpers/StringHelper.php:

    if (!function_exists('terminated_string')) {
        function terminated_string(string $string, array $terminators): string {
            return (new TerminatedString($string, $terminators))->get();
        }
    }
    

    Use it in controllers/validators:

    $cleanInput = terminated_string($request->input, ['#', '--']);
    
  3. Validation Rule: Extend Laravel’s validation to enforce string termination:

    use Illuminate\Validation\Rule;
    
    Rule::make(function ($attribute, $value, $terminators) {
        $terminated = new TerminatedString($value, $terminators);
        return strlen($terminated->get()) <= $this->maxLength;
    })->terminators(['#', '--']);
    

    Usage in Form Request:

    $this->rules = [
        'query' => ['required', Rule::terminators(['#'])->max(100)],
    ];
    
  4. Service Integration: Register the class in Laravel’s service container for dependency injection:

    $this->app->bind(TerminatedString::class, function () {
        return new TerminatedString($this->input, $this->terminators);
    });
    

    Inject into a service:

    public function __construct(private TerminatedString $terminatedString) {}
    

Advanced Patterns

  1. Dynamic Terminators: Fetch terminators from config or environment:

    $terminators = config('app.string_terminators');
    $string = new TerminatedString($input, $terminators);
    
  2. Batch Processing: Process arrays of strings (e.g., log files, CSV rows):

    $logLines = file('app.log');
    $cleanLines = array_map(
        fn($line) => (new TerminatedString($line, ["\n", ' ']))->get(),
        $logLines
    );
    
  3. Custom Logic Extension: Extend the class for additional functionality (e.g., trimming whitespace):

    class ExtendedTerminatedString extends TerminatedString {
        public function getTrimmed(): string {
            return trim(parent::get());
        }
    }
    

Gotchas and Tips

Pitfalls

  1. No Terminator Found:

    • The package returns the original string if no terminator is found. Handle this explicitly:
      $result = $string->get();
      if ($result === $input) {
          // No terminator found; handle accordingly
      }
      
  2. Multi-byte Characters:

    • The package may not handle Unicode terminators (e.g., \u2028) correctly. Test with non-ASCII input:
      $string = new TerminatedString("text\u2028hidden", ['\u2028']);
      // May not work as expected; use `mb_*` functions if needed.
      
  3. PHP 8.x Compatibility:

    • The package was last updated in 2019. Test with PHP 8.1+ for:
      • Constructor property promotion.
      • Named arguments.
      • Deprecated functions (e.g., create_function).
  4. Performance with Large Strings:

    • For very long strings (e.g., >1MB), benchmark against native substr() or preg_split():
      $nativeResult = substr($input, 0, strpos($input, $terminator));
      
  5. Case Sensitivity:

    • Terminators are case-sensitive. Use array_map('strtolower', $terminators) if case-insensitive matching is needed.

Debugging Tips

  1. Verify Terminators:

    • Ensure terminators are passed as an array:
      // Wrong: new TerminatedString($input, '#')
      // Right: new TerminatedString($input, ['#'])
      
  2. Check for Hidden Characters:

    • Use var_export() to inspect strings for invisible terminators:
      var_export($input); // Reveals \n, \r, etc.
      
  3. Edge Cases:

    • Test with:
      • Empty strings.
      • Strings with no terminators.
      • Terminators at the start of the string.
      • Multiple consecutive terminators.
  4. Logging:

    • Log input/output for debugging:
      Log::debug('Input', ['string' => $input, 'terminators' => $terminators]);
      Log::debug('Output', ['result' => $result]);
      

Configuration Quirks

  1. Composer Lock:

    • Pin the package version to avoid unexpected updates:
      "require": {
          "webignition/disallowed-character-terminated-string": "1.0.0"
      }
      
  2. Autoloading:

    • Ensure the package is autoloaded in composer.json:
      "autoload": {
          "psr-4": {
              "webignition\\DisallowedCharacterTerminatedString\\": "vendor/webignition/disallowed-character-terminated-string/src/"
          }
      }
      

Extension Points

  1. Custom Terminator Logic:

    • Override the get() method to add pre/post-processing:
      class CustomTerminatedString extends TerminatedString {
          public function get(): string {
              $result = parent::get();
              return str_replace([' ', "\t"], '', $result); // Remove whitespace
          }
      }
      
  2. Laravel Facade:

    • Create a facade for cleaner syntax:
      // app/Providers/AppServiceProvider.php
      use Illuminate\Support\Facades\Facade;
      
      Facade::register('TerminatedString', function () {
          return new \webignition\DisallowedCharacterTerminatedString\TerminatedString(...);
      });
      
      Usage:
      $result = TerminatedString::make($input, ['#'])->get();
      
  3. Integration with Laravel Collectives:

    • Combine with laravelcollective/html for HTML comment stripping:
      use Collective\Html\HtmlBuilder;
      
      $cleanHtml = HtmlBuilder::stripTags(
          (new TerminatedString($dirtyHtml, ['<!--', '-->']))->get()
      );
      

Laravel-Specific Tips

  1. Artisan Commands:

    • Use the package in Artisan commands for CLI-based string processing:
      $this->info((new TerminatedString($this->argument('input'), ['#']))->get());
      
  2. Blade Directives:

    • Create a Blade directive for frontend string cleaning:
      Blade::directive('terminate', function ($expression) {
          return "<?php echo (new \\webignition\\DisallowedCharacterTerminatedString\\TerminatedString({$expression[0]}, {$expression[1]}))->get(); ?>";
      });
      
      Usage in Blade:
      @terminate($string, ['#'])
      
  3. Event Listeners:

    • Process strings in event listeners (e.g., sanitizing user-generated content):
      public function handle(ContentCreated $event) {
          $event->content = (new TerminatedString($event->content,
      
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.
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts
earls/stork-command-queue-bundle