PHPackages                             baraja-core/video-token - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. baraja-core/video-token

ActiveLibrary[Image &amp; Media](/categories/media)

baraja-core/video-token
=======================

Parse video token from user string or URL.

v1.0.1(4y ago)16.5kPHPPHP ^8.0CI passing

Since Jul 12Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/video-token)[ Packagist](https://packagist.org/packages/baraja-core/video-token)[ Docs](https://github.com/baraja-core/video-token)[ RSS](/packages/baraja-core-video-token/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (2)Dependencies (7)Versions (4)Used By (0)

🎬 Video Token
=============

[](#-video-token)

A lightweight PHP library for parsing and normalizing video tokens from YouTube and Vimeo URLs. Automatically extracts video identifiers from various URL formats and provides a unified interface for generating embed URLs and thumbnail images.

✨ Key Features
--------------

[](#-key-features)

- **Automatic provider detection** - Identifies YouTube or Vimeo based on URL structure or token format
- **Multiple URL format support** - Handles standard URLs, short URLs, embed codes, and URL-encoded strings
- **Token validation** - Validates token format and length for each provider
- **Embed URL generation** - Creates ready-to-use iframe embed URLs
- **Thumbnail retrieval** - Fetches video thumbnail URLs (direct for YouTube, via API for Vimeo)
- **Zero dependencies** - Pure PHP implementation with no external dependencies
- **Strict typing** - Full PHP 8.0+ strict type declarations

🏗️ Architecture
---------------

[](#️-architecture)

The library consists of a single immutable value object `VideoToken` that encapsulates:

```
┌─────────────────────────────────────────────────────────────┐
│                       VideoToken                            │
├─────────────────────────────────────────────────────────────┤
│  Input: URL or Token + Provider                             │
│    │                                                        │
│    ▼                                                        │
│  ┌─────────────────────┐                                    │
│  │  URL Parser         │ ─── Detects domain & extracts path │
│  └─────────────────────┘                                    │
│    │                                                        │
│    ▼                                                        │
│  ┌─────────────────────┐                                    │
│  │  Provider Resolver  │ ─── YouTube: 11-char alphanumeric  │
│  │                     │ ─── Vimeo: 8-digit numeric         │
│  └─────────────────────┘                                    │
│    │                                                        │
│    ▼                                                        │
│  ┌─────────────────────┐                                    │
│  │  Token Validator    │ ─── Max 32 characters              │
│  └─────────────────────┘                                    │
│    │                                                        │
│    ▼                                                        │
│  Output: Validated token + provider                         │
│    • getToken()        → Raw video identifier               │
│    • getProvider()     → 'youtube' | 'vimeo'                │
│    • getUrl()          → Embed URL                          │
│    • getThumbnailUrl() → Thumbnail image URL                │
└─────────────────────────────────────────────────────────────┘

```

🎯 Supported Providers
---------------------

[](#-supported-providers)

### YouTube

[](#youtube)

The library recognizes YouTube videos from the following domains:

- `youtube.com`
- `youtu.be`
- `youtube-nocookie.com`
- `yt.be`

**Supported URL formats:**

- Standard watch URL: `https://www.youtube.com/watch?v=VIDEO_ID`
- Short URL: `https://youtu.be/VIDEO_ID`
- Embed URL: `https://www.youtube.com/embed/VIDEO_ID`
- Various legacy formats: `/v/`, `/vi/`, `/e/`, `ytscreeningroom?v=`
- URL-encoded formats: `watch%3Fv%3D`
- Playlist URLs with video: `watchv=VIDEO_ID&list=...`

YouTube tokens are 11 characters long, containing alphanumeric characters, hyphens, and underscores.

### Vimeo

[](#vimeo)

The library recognizes Vimeo videos from:

- `vimeo.com`
- `player.vimeo.com`

Vimeo tokens are 8-digit numeric identifiers.

📦 Installation
--------------

[](#-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/video-token) and [GitHub](https://github.com/baraja-core/video-token).

To install, simply use the command:

```
$ composer require baraja-core/video-token
```

**Requirements:**

- PHP 8.0 or higher

🚀 Basic Usage
-------------

[](#-basic-usage)

### Creating a VideoToken from URL

[](#creating-a-videotoken-from-url)

```
use Baraja\VideoToken\VideoToken;

// From a YouTube URL
$token = new VideoToken('https://www.youtube.com/watch?v=dQw4w9WgXcQ');

echo $token->getToken();    // dQw4w9WgXcQ
echo $token->getProvider(); // youtube
```

### Creating a VideoToken with explicit provider

[](#creating-a-videotoken-with-explicit-provider)

```
use Baraja\VideoToken\VideoToken;

// When you already have the token and know the provider
$token = new VideoToken('dQw4w9WgXcQ', 'youtube');
```

### Getting the embed URL

[](#getting-the-embed-url)

```
use Baraja\VideoToken\VideoToken;

$token = new VideoToken('https://www.youtube.com/watch?v=dQw4w9WgXcQ');

echo $token->getUrl();
// YouTube: https://www.youtube.com/embed/dQw4w9WgXcQ?rel=0
// Vimeo:   https://player.vimeo.com/video/12345678
```

### Getting the thumbnail URL

[](#getting-the-thumbnail-url)

```
use Baraja\VideoToken\VideoToken;

// YouTube - direct URL, no API call needed
$youtube = new VideoToken('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
echo $youtube->getThumbnailUrl();
// https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg

// Vimeo - fetches from Vimeo oEmbed API
$vimeo = new VideoToken('https://vimeo.com/12345678');
echo $vimeo->getThumbnailUrl();
// Returns thumbnail URL from Vimeo API response
```

### Working with Vimeo

[](#working-with-vimeo)

```
use Baraja\VideoToken\VideoToken;

$token = new VideoToken('https://vimeo.com/76979871');

echo $token->getToken();    // 76979871
echo $token->getProvider(); // vimeo
echo $token->getUrl();      // https://player.vimeo.com/video/76979871
```

🔍 Static URL Parser
-------------------

[](#-static-url-parser)

For cases where you only need to extract a YouTube token without creating a full `VideoToken` object:

```
use Baraja\VideoToken\VideoToken;

// Parse various YouTube URL formats
$token = VideoToken::parseYouTubeTokenByUrl('watch?v=dQw4w9WgXcQ');
// Returns: dQw4w9WgXcQ

$token = VideoToken::parseYouTubeTokenByUrl('embed/dQw4w9WgXcQ');
// Returns: dQw4w9WgXcQ

$token = VideoToken::parseYouTubeTokenByUrl('dQw4w9WgXcQ');
// Returns: dQw4w9WgXcQ (exact match)

// User channels return null (no video token)
$token = VideoToken::parseYouTubeTokenByUrl('user/SomeChannel');
// Returns: null
```

⚠️ Error Handling
-----------------

[](#️-error-handling)

The library throws `\InvalidArgumentException` in the following cases:

```
use Baraja\VideoToken\VideoToken;

// Token too long (max 32 characters)
try {
    new VideoToken('this_token_is_way_too_long_to_be_valid_video_id');
} catch (\InvalidArgumentException $e) {
    // Video token "..." is too long.
}

// Invalid URL format
try {
    new VideoToken('https://invalid-video-site.com/video/123');
} catch (\InvalidArgumentException $e) {
    // Token or URL "..." is invalid.
}

// Missing provider when token format is ambiguous
try {
    new VideoToken('ambiguous-token');
} catch (\InvalidArgumentException $e) {
    // Provider for token "..." is mandatory.
}
```

The `getUrl()` method throws `\LogicException` if called with an unsupported provider (should not happen with normal usage).

⚡ Performance Considerations
----------------------------

[](#-performance-considerations)

### Thumbnail URL Caching

[](#thumbnail-url-caching)

**Important:** The `getThumbnailUrl()` method for Vimeo videos makes an HTTP request to the Vimeo oEmbed API. Always cache the result:

```
$token = new VideoToken('https://vimeo.com/76979871');

// Cache this result!
$thumbnailUrl = $cache->get('vimeo_thumb_' . $token->getToken(), function () use ($token) {
    return $token->getThumbnailUrl();
});
```

YouTube thumbnails are generated using a predictable URL pattern and don't require API calls.

### Immutability

[](#immutability)

The `VideoToken` object is immutable. Once created, the token and provider cannot be changed. This makes it safe to pass around and cache without defensive copying.

🔧 Provider Constants
--------------------

[](#-provider-constants)

The library provides constants for provider identification:

```
use Baraja\VideoToken\VideoToken;

VideoToken::PROVIDER_YOUTUBE; // 'youtube'
VideoToken::PROVIDER_VIMEO;   // 'vimeo'

// Use in comparisons
if ($token->getProvider() === VideoToken::PROVIDER_YOUTUBE) {
    // YouTube-specific logic
}
```

🌐 Use Cases
-----------

[](#-use-cases)

### Embedding videos in HTML

[](#embedding-videos-in-html)

```
$token = new VideoToken($_POST['video_url']);

$html = sprintf(
    '',
    htmlspecialchars($token->getUrl(), ENT_QUOTES, 'UTF-8')
);
```

### Storing normalized video references

[](#storing-normalized-video-references)

```
// User submits various URL formats
$input = 'https://youtu.be/dQw4w9WgXcQ?t=42';

$token = new VideoToken($input);

// Store only what you need
$database->insert('videos', [
    'token' => $token->getToken(),      // dQw4w9WgXcQ
    'provider' => $token->getProvider(), // youtube
]);
```

### Video preview cards

[](#video-preview-cards)

```
$token = new VideoToken($videoUrl);

echo '';
echo '  ';
echo '  Watch video';
echo '';
```

👤 Author
--------

[](#-author)

**Jan Barášek**Website:

📄 License
---------

[](#-license)

`baraja-core/video-token` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/video-token/blob/master/LICENSE) file for more details.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance52

Moderate activity, may be stable

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~162 days

Total

2

Last Release

1606d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (16 commits)")

---

Tags

parserphptokenvideovimeoyoutube

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-video-token/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-video-token/health.svg)](https://phpackages.com/packages/baraja-core-video-token)
```

###  Alternatives

[milon/barcode

Barcode generator like Qr Code, PDF417, C39, C39+, C39E, C39E+, C93, S25, S25+, I25, I25+, C128, C128A, C128B, C128C, 2-Digits UPC-Based Extention, 5-Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI (Variation of Plessey code)

1.5k13.3M39](/packages/milon-barcode)[bkwld/croppa

Image thumbnail creation through specially formatted URLs for Laravel

510496.0k23](/packages/bkwld-croppa)[goat1000/svggraph

Generates SVG graphs

132849.6k3](/packages/goat1000-svggraph)[cohensive/embed

Media Embed (for Laravel or as a standalone).

120370.4k](/packages/cohensive-embed)[netresearch/rte-ckeditor-image

Image support in CKEditor for the TYPO3 ecosystem - by Netresearch

63991.3k4](/packages/netresearch-rte-ckeditor-image)[humanmade/tachyon-plugin

Rewrites WordPress image URLs to use Tachyon

87338.5k2](/packages/humanmade-tachyon-plugin)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
