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

Shariff Laravel Package

heise/shariff

PHP backend for Shariff that fetches social share counts without client-side requests to social networks. Supports Buffer, Facebook, Pinterest, Reddit, Xing, VK and more, with domain whitelisting and configurable caching (filesystem or Laminas adapters).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel (Updated for v11.0.0)

  1. Install via Composer (PHP 8.1+ required):

    composer require heise/shariff:^11.0
    
  2. Create a dedicated route (e.g., routes/web.php):

    Route::get('/shariff', [ShariffController::class, 'index']);
    
  3. Basic Controller Implementation (app/Http/Controllers/ShariffController.php):

    use Heise\Shariff\Backend;
    
    class ShariffController extends Controller
    {
        public function index()
        {
            $options = [
                'domains' => ['yourdomain.com'],
                'services' => ['Facebook', 'Twitter', 'LinkedIn'], // Updated default services (StumbleUpon removed)
                'cache' => ['ttl' => 3600]
            ];
    
            $shariff = new Backend($options);
            $url = urldecode(request('url'));
            $counts = $shariff->get($url);
    
            return response()->json($counts);
        }
    }
    
  4. Frontend Integration (unchanged):

    <div class="shariff" data-url="https://yourdomain.com/article" data-services="facebook,twitter"></div>
    <script src="https://cdn.jsdelivr.net/npm/shariff@latest/dist/shariff.min.js"></script>
    

Implementation Patterns

1. Service-Specific Configuration (Updated for v11.0.0)

  • Facebook Graph API v25.0: Now uses the latest API version. Requires updated credentials:
    $options = [
        'Facebook' => [
            'app_id' => env('FACEBOOK_APP_ID'),
            'secret' => env('FACEBOOK_APP_SECRET'),
            'graph_version' => 'v25.0' // Explicitly set (default in v11.0.0)
        ]
    ];
    
  • Removed Services: StumbleUpon and Flattr are no longer supported. Update frontend calls accordingly.

2. Caching Strategies (Laravel Integration)

  • Laravel Cache: Replace default cache with Laravel’s cache (unchanged):
    'cacheClass' => \App\Services\LaravelCache::class,
    'cache' => ['ttl' => 3600]
    
  • Note: Ensure your Laravel cache driver (e.g., file, redis) is configured in .env.

3. Domain Whitelisting (Unchanged)

  • Restrict shares to specific domains:
    'domains' => [
        'blog.yourdomain.com',
        'news.yourdomain.com'
    ]
    

4. Dynamic Service Enablement (Unchanged)

  • Enable/disable services dynamically:
    $services = explode(',', request('services', 'facebook,twitter,linkedin'));
    $options['services'] = array_filter($services);
    

5. Logging Failures (Updated for PHP 8.2+)

  • Extend Backend to log service errors (now compatible with PHP 8.2+):
    use Psr\Log\LoggerInterface;
    
    class ShariffBackend extends Backend {
        public function __construct(array $options, LoggerInterface $logger = null)
        {
            parent::__construct($options, $logger); // Logger is now optional in v11.0.0
        }
    }
    

Gotchas and Tips

1. PHP Version Requirements (Breaking Change)

  • Issue: v11.0.0 drops support for PHP 7.4 and 8.0. Requires PHP 8.1+.
  • Fix: Update your server/php environment:
    # Example for Laravel Forge
    forge php:8.2
    
  • Verify: Run php -v to confirm compatibility.

2. Facebook Graph API v25.0 (Breaking Change)

  • Issue: Facebook’s API version is now v25.0 (default in v11.0.0). Older credentials may fail.
  • Fix:
    1. Update your Facebook App’s Valid OAuth Redirect URIs in the Facebook Developers Dashboard.
    2. Reconfigure credentials:
      'Facebook' => [
          'app_id' => env('FACEBOOK_APP_ID'),
          'secret' => env('FACEBOOK_APP_SECRET'),
          'graph_version' => 'v25.0' // Explicitly set for clarity
      ]
      
  • Note: Facebook may require review for new API permissions.

3. Removed Services (Breaking Change)

  • Issue: StumbleUpon and Flattr are no longer supported. Frontend calls to these services will fail.
  • Fix:
    • Remove stumbleupon from frontend data-services:
      <div class="shariff" data-services="facebook,twitter">...</div>
      
    • Update backend whitelisting if needed:
      'services' => ['Facebook', 'Twitter', 'LinkedIn'] // Example updated list
      

4. URL Encoding Pitfalls (Unchanged)

  • Issue: Frontend sends raw URLs, but backend expects URL-encoded strings.
  • Fix: Always urldecode():
    $url = urldecode(request('url'));
    

5. Cache Directory Permissions (Unchanged)

  • Issue: Default cache directory may lack write permissions.
  • Fix: Specify a custom directory:
    'cache' => [
        'cacheDir' => storage_path('app/shariff-cache'),
        'ttl' => 3600
    ]
    
    Run:
    mkdir -p storage/app/shariff-cache
    chmod -R 775 storage/app/shariff-cache
    

6. Laravel Service Provider Integration (Updated for PHP 8.2+)

  • Tip: Bind the Backend class to Laravel’s container (now type-hinted for PHP 8.2+):
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Heise\Shariff\Backend::class, function ($app) {
            return new Backend(config('shariff.options'), $app->make(LoggerInterface::class));
        });
    }
    
  • Config Example (config/shariff.php):
    return [
        'options' => [
            'domains' => ['yourdomain.com'],
            'services' => ['Facebook', 'Twitter'],
            'cache' => ['ttl' => 3600],
            'Facebook' => [
                'app_id' => env('FACEBOOK_APP_ID'),
                'secret' => env('FACEBOOK_APP_SECRET'),
                'graph_version' => 'v25.0'
            ]
        ]
    ];
    

7. Rate Limiting and Timeouts (Unchanged)

  • Issue: Slow services may timeout.
  • Fix: Adjust Guzzle timeouts:
    'client' => [
        'timeout' => 10.0,
        'connect_timeout' => 3.0
    ]
    

8. Testing Edge Cases (Updated for PHP 8.2+)

  • Test Scenarios:
    1. Invalid URLs (e.g., http://invalid..com).
    2. Disallowed domains.
    3. Service-specific failures (mock Guzzle responses).
  • Example Test (PHP 8.2+ compatible):
    public function test_shariff_with_invalid_url()
    {
        $shariff = new Backend(['domains' => ['example.com']]);
        $this->expectException(\InvalidArgumentException::class);
        $shariff->get('http://invalid..com');
    }
    

9. Debugging Tips (Unchanged)

  • Enable Guzzle Debugging:
    'client' => [
        'debug' => fopen(storage_path('logs/shariff-debug.log'), 'w')
    ]
    
  • Log Raw Responses: Override Backend::get() to log outputs.

10. Frontend Integration Notes (Unchanged)

  • CORS: Ensure your backend allows requests from the frontend domain:
    // Middleware: HandleCors
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET');
    }
    

11. PHP 8.2+ Type Safety

  • New Feature: v11.0.0 leverages PHP 8.2’s features (e.g.,
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui