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

Get In Laravel Package

igorw/get-in

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require igorw/get-in
    

    Add the namespace to your composer.json aliases (optional but recommended):

    "autoload": {
        "files": ["vendor/igorw/get-in/src/functions.php"]
    }
    

    Run composer dump-autoload.

  2. First Use Case: Replace a nested isset check with get_in:

    // Before
    $darkMode = isset($user['preferences']['theme']['darkMode'])
        ? $user['preferences']['theme']['darkMode']
        : false;
    
    // After
    $darkMode = igorw\get_in($user, ['preferences', 'theme', 'darkMode'], false);
    
  3. Key Functions to Explore:

    • get_in: Fetch nested values with defaults.
    • assoc_in: Set nested values (creates intermediate arrays if needed).
    • update_in: Modify nested values via a callback.

Where to Look First

  • README.md: Focus on the Usage section for syntax and examples.
  • Source Code: src/functions.php (100 lines) to understand edge cases.
  • Laravel Integration: Pair with Arr::get() for hybrid traversal (e.g., get_in($request->all(), ['user', 'id'])).

Implementation Patterns

Core Workflows

1. Data Fetching with Fallbacks

Pattern: Replace repetitive isset checks or Arr::get with defaults.

// API Response Handling
$userId = igorw\get_in($apiResponse, ['data', 'user', 'id'], null);
if ($userId) {
    // Proceed
}

// Config Overrides
$timeout = igorw\get_in(config('services'), ['api', 'timeout'], 30);

2. Nested Data Updates

Pattern: Use update_in for conditional or dynamic modifications.

// Sanitize API Input
$cleanedData = igorw\update_in(
    $request->all(),
    ['user', 'name'],
    fn($name) => trim(strtolower($name))
);

// Increment a Counter
$data = igorw\update_in($stats, ['visits'], fn($count) => $count + 1);

3. Dynamic Path Traversal

Pattern: Build paths dynamically (e.g., from user input or config).

$path = explode('.', $request->input('path'));
$value = igorw\get_in($data, $path, 'default');

4. Laravel-Specific Integrations

Pattern: Combine with Laravel helpers for seamless adoption.

// Eloquent Relationships
$user = User::find(1);
$email = igorw\get_in($user->toArray(), ['profile', 'contact', 'email'], 'no-email@example.com');

// Request Data
$theme = igorw\get_in($request->json()->all(), ['preferences', 'theme'], 'light');

// Config Merging
$merged = igorw\assoc_in(
    config('app.settings'),
    ['features', 'analytics'],
    igorw\get_in($envConfig, ['analytics'], false)
);

5. Functional Composition

Pattern: Chain operations for complex transformations.

$processed = igorw\update_in(
    $data,
    ['user', 'metadata', 'lastActive'],
    fn($timestamp) => now()->diffInSeconds($timestamp)
);

Integration Tips

  • Avoid Overuse: Prefer Arr::get() for simple, flat traversals (e.g., Arr::get($array, 'key')).
  • Type Safety: Use PHP 8.1+ return types with get_in:
    /** @return string|null */
    $value = igorw\get_in($data, ['path'], null);
    
  • Testing: Mock get_in in unit tests:
    $this->partialMock()
         ->shouldReceive('get_in')
         ->with(['data', 'key'])
         ->andReturn('mocked');
    
  • Performance: For hot paths, benchmark against native PHP:
    // Benchmark: get_in vs. manual traversal
    $data = ['a' => ['b' => ['c' => 1]]];
    $start = microtime(true);
    igorw\get_in($data, ['a', 'b', 'c']);
    $time = microtime(true) - $start;
    

Gotchas and Tips

Pitfalls

  1. Non-Array Inputs:

    • Throws InvalidArgumentException if the first argument isn’t traversable.
    • Fix: Validate input:
      if (!is_array($data)) {
          throw new \InvalidArgumentException('Input must be an array.');
      }
      
  2. Mutable State in update_in:

    • Modifies the original array unless you clone it first:
      $newData = igorw\update_in(clone $data, ['path'], $callback);
      
  3. Default Value Confusion:

    • Defaults are returned only if the path doesn’t exist entirely (not for intermediate null values).
      $data = ['a' => null];
      igorw\get_in($data, ['a', 'b'], 'default'); // Returns null (not 'default')
      
  4. Key Collisions:

    • If a key in the path is 0 or a string that could be misinterpreted as an array index, behavior may vary.
    • Workaround: Use string keys consistently (e.g., ['0', 'key'] instead of [0, 'key']).
  5. IDE Autocompletion:

    • Some IDEs (e.g., PHPStorm) may not autocomplete dynamic paths like ['user', 'profile'].
    • Tip: Use static analysis tools like phpstan to catch invalid paths early.

Debugging Tips

  • Enable Error Reporting:

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

    Helps catch InvalidArgumentException for non-array inputs.

  • Log Paths:

    $path = ['user', 'profile', 'email'];
    $value = igorw\get_in($data, $path, null);
    logger()->debug("Path {$path[0]}->...->{$path[count($path)-1]}: {$value}");
    
  • Validate Paths:

    function isValidPath(array $data, array $path): bool {
        $current = $data;
        foreach ($path as $key) {
            if (!array_key_exists($key, $current)) {
                return false;
            }
            $current = $current[$key];
        }
        return true;
    }
    

Configuration Quirks

  • No Global Config: The package is stateless; all behavior is runtime-driven.
  • Custom Resolvers: Extend functionality by wrapping get_in:
    function getInWithFallback(array $data, array $path, $default = null, callable $fallback = null) {
        $value = igorw\get_in($data, $path, $default);
        return $fallback ? $fallback($value) : $value;
    }
    

Extension Points

  1. Custom Default Factories:

    function get_in_with_factory(array $data, array $path, callable $factory) {
        return igorw\get_in($data, $path, $factory());
    }
    
  2. Path Normalization:

    function normalizePath(array $path): array {
        return array_map('strval', $path); // Ensure all keys are strings
    }
    
  3. Laravel Service Provider:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        app()->bind('getIn', function() {
            return new class {
                public function __invoke(array $data, array $path, $default = null) {
                    return igorw\get_in($data, $path, $default);
                }
            };
        });
    }
    
  4. JSONPath-like Queries:

    function jsonPathGet(array $data, string $query) {
        $path = explode('.', $query);
        return igorw\get_in($data, $path);
    }
    

Laravel-Specific Gotchas

  • Request Data:

    • get_in($request->all(), ['user', 'id']) works, but ensure $request->all() returns an array.
    • Fix: Use $request->json()->all() for JSON requests.
  • Eloquent Models:

    • `get_in($
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle