PHPackages                             amirmahvari/wb-utilities - 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. amirmahvari/wb-utilities

ActiveLibrary

amirmahvari/wb-utilities
========================

A collection of utility classes for WordPress development including Excel/CSV/PDF Export, Query Builder, and common utilities

03PHP

Since Oct 23Pushed 6mo agoCompare

[ Source](https://github.com/amirmahvari/wb-utilities)[ Packagist](https://packagist.org/packages/amirmahvari/wb-utilities)[ RSS](/packages/amirmahvari-wb-utilities/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

WB Utilities Package
====================

[](#wb-utilities-package)

🔧 Collection of powerful PHP utilities for WordPress and general web development with full Persian/Jalali support.

Features
--------

[](#features)

✨ **Multi-Format Export** - Export to Excel (xlsx), CSV, PDF with RTL support
🗄️ **Fluent Query Builder** - Works with WordPress wpdb and PDO
🛠️ **30+ Helper Functions** - Arrays, strings, Persian text, dates, JSON
🌐 **Persian/Jalali Support** - Full support for Persian characters and calendar
📦 **WordPress Agnostic** - Works in any PHP project (with WordPress optimizations)

Installation
------------

[](#installation)

```
composer require amirmahvari/wb-utilities
```

Quick Start
-----------

[](#quick-start)

### Excel/CSV/PDF Export

[](#excelcsvpdf-export)

```
use Amirmahvari\WbUtilities\ExcelExporter;

// One-line export
ExcelExporter::quick($data, 'report.xlsx', $columns, 'excel');

// Advanced usage with format selection
$exporter = new ExcelExporter();
$exporter->setFormat('csv')  // 'excel', 'csv', 'pdf'
         ->setData($data)
         ->setColumns([
             'id' => 'شناسه',
             'name' => 'نام',
             'email' => 'ایمیل'
         ])
         ->setFilename('گزارش-کاربران')
         ->download();

// Save to server instead of download
$exporter->generate('/path/to/save/report.xlsx');
```

### Query Builder

[](#query-builder)

```
use Amirmahvari\WbUtilities\QueryBuilder;

// Basic select
$users = QueryBuilder::table('wp_users')
    ->select('ID, display_name, user_email')
    ->where('user_status', 0)
    ->orderBy('ID', 'DESC')
    ->limit(10)
    ->get();

// Joins
$posts = QueryBuilder::table('wp_posts as p')
    ->select('p.*, u.display_name')
    ->join('wp_users as u', 'p.post_author', '=', 'u.ID')
    ->where('p.post_status', 'publish')
    ->get();

// Insert
QueryBuilder::table('wp_custom_table')->insert([
    'title' => 'Test',
    'status' => 'active',
    'created_at' => date('Y-m-d H:i:s')
]);

// Update
QueryBuilder::table('wp_users')
    ->where('ID', 1)
    ->update(['display_name' => 'New Name']);

// Delete
QueryBuilder::table('wp_posts')
    ->where('post_status', 'trash')
    ->delete();

// Advanced conditions
$products = QueryBuilder::table('products')
    ->whereIn('category_id', [1, 2, 3])
    ->whereBetween('price', [100, 500])
    ->whereLike('name', '%phone%')
    ->whereNull('deleted_at')
    ->get();

// Aggregations
$count = QueryBuilder::table('wp_posts')->count();
$exists = QueryBuilder::table('wp_users')->where('user_email', 'test@example.com')->exists();
$ids = QueryBuilder::table('wp_posts')->pluck('ID');

// Raw queries
$results = QueryBuilder::raw('SELECT * FROM wp_users WHERE ID > ?', [10]);
```

### Utility Helpers

[](#utility-helpers)

```
use Amirmahvari\WbUtilities\Utility;

// ═══════════════════════════════════════
// Persian Text Operations
// ═══════════════════════════════════════
Utility::sanitize_persian_text('سلام دنیا');
Utility::is_persian('این متن فارسی است');
Utility::convert_to_persian_numbers('123456');  // ۱۲۳۴۵۶
Utility::convert_to_english_numbers('۱۲۳۴۵۶');  // 123456

// ═══════════════════════════════════════
// Array Operations
// ═══════════════════════════════════════
$users = [
    ['id' => 1, 'name' => 'Ali'],
    ['id' => 2, 'name' => 'Sara']
];

Utility::array_pluck($users, 'name');  // ['Ali', 'Sara']
Utility::array_key_value($users, 'id', 'name');  // [1 => 'Ali', 2 => 'Sara']

Utility::array_where($users, function($user) {
    return $user['id'] > 1;
});

// Dot notation
$config = ['database' => ['host' => 'localhost']];
Utility::array_get($config, 'database.host');  // 'localhost'
Utility::array_set($config, 'database.port', 3306);

Utility::array_flatten([1, [2, [3, 4]]], 5]);  // [1, 2, 3, 4, 5]

// ═══════════════════════════════════════
// Date & Time (Jalali Support)
// ═══════════════════════════════════════
Utility::to_jalali_date('2024-01-15');  // '1402/10/25'
Utility::to_jalali_date('2024-01-15 14:30:00', true);  // '1402/10/25 14:30'

// ═══════════════════════════════════════
// String Operations
// ═══════════════════════════════════════
Utility::create_slug('محصول جدید');  // 'محصول-جدید'
Utility::truncate('This is a long text', 10);  // 'This is a...'
Utility::random_string(16);  // Random string
Utility::starts_with('Hello World', 'Hello');  // true
Utility::ends_with('test.php', '.php');  // true
Utility::contains('Hello World', 'World');  // true

// ═══════════════════════════════════════
// Formatting
// ═══════════════════════════════════════
Utility::format_number(1234567);  // '1,234,567'
Utility::format_bytes(1048576);  // '1 MB'
Utility::format_price(25000, 'تومان');  // '25,000 تومان'

// ═══════════════════════════════════════
// JSON Operations
// ═══════════════════════════════════════
Utility::is_json('{"key": "value"}');  // true
Utility::json_decode_safe('invalid json', ['default' => 'value']);

// ═══════════════════════════════════════
// Validation
// ═══════════════════════════════════════
Utility::is_email('test@example.com');
Utility::is_url('https://example.com');
Utility::is_mobile('09123456789');

// ═══════════════════════════════════════
// Sanitization
// ═══════════════════════════════════════
Utility::sanitize_mobile('0912-345-6789');  // '09123456789'
Utility::sanitize_number('1,234.56 تومان');  // '1234.56'
```

Full API Reference
------------------

[](#full-api-reference)

### ExcelExporter Methods

[](#excelexporter-methods)

MethodDescription`setData(array $data)`Set data to export`setColumns(array $columns)`Set column mapping (key =&gt; label)`setFilename(string $name)`Set output filename (without extension)`setFormat(string $format)`Set format: 'excel', 'csv', 'pdf'`download()`Download file to browser`generate(?string $path)`Save to server path`static quick($data, $filename, $columns, $format)`One-line export### QueryBuilder Methods

[](#querybuilder-methods)

MethodDescription`table(string $table)`Set table name (static factory)`select(string $columns)`Select columns`where($column, $operator, $value)`Add WHERE condition`orWhere($column, $operator, $value)`Add OR WHERE`whereIn($column, array $values)`WHERE IN condition`whereNull($column)`WHERE IS NULL`whereBetween($column, $min, $max)`WHERE BETWEEN`whereLike($column, $value)`WHERE LIKE`join($table, $first, $operator, $second)`INNER JOIN`leftJoin(...)`LEFT JOIN`rightJoin(...)`RIGHT JOIN`orderBy($column, $direction)`ORDER BY`groupBy($column)`GROUP BY`limit(int $limit)`LIMIT`offset(int $offset)`OFFSET`get($db = null)`Execute and get results`first($db = null)`Get first result`insert(array $data, $db = null)`Insert record`update(array $data, $db = null)`Update records`delete($db = null)`Delete records`count($db = null)`Count records`exists($db = null)`Check if exists`pluck($column, $db = null)`Get column values`static raw($sql, $bindings, $db)`Execute raw query### Utility Methods

[](#utility-methods)

**Persian Text:** `sanitize_persian_text()`, `is_persian()`, `convert_to_persian_numbers()`, `convert_to_english_numbers()`

**Arrays:** `array_pluck()`, `array_key_value()`, `array_where()`, `array_flatten()`, `array_get()`, `array_set()`, `array_has()`, `array_except()`, `array_only()`

**Strings:** `create_slug()`, `truncate()`, `random_string()`, `starts_with()`, `ends_with()`, `contains()`

**Dates:** `to_jalali_date()`

**Formatting:** `format_number()`, `format_bytes()`, `format_price()`

**Validation:** `is_email()`, `is_url()`, `is_mobile()`, `is_json()`

**Sanitization:** `sanitize_mobile()`, `sanitize_number()`

**JSON:** `json_decode_safe()`

Use Cases
---------

[](#use-cases)

### Export WordPress Users to Excel

[](#export-wordpress-users-to-excel)

```
$users = get_users();
$data = array_map(function($user) {
    return [
        'id' => $user->ID,
        'name' => $user->display_name,
        'email' => $user->user_email
    ];
}, $users);

ExcelExporter::quick($data, 'users.xlsx', [
    'id' => 'شناسه',
    'name' => 'نام',
    'email' => 'ایمیل'
], 'excel');
```

### Complex Query with WordPress

[](#complex-query-with-wordpress)

```
$products = QueryBuilder::table('wp_posts as p')
    ->select('p.ID, p.post_title, pm.meta_value as price')
    ->join('wp_postmeta as pm', 'p.ID', '=', 'pm.post_id')
    ->where('p.post_type', 'product')
    ->where('p.post_status', 'publish')
    ->where('pm.meta_key', '_price')
    ->whereBetween('pm.meta_value', [100, 1000])
    ->orderBy('pm.meta_value', 'DESC')
    ->get();
```

Requirements
------------

[](#requirements)

- **PHP:** &gt;= 7.4
- **Composer:** Latest version
- **Dependencies:**
    - spatie/simple-excel: ^3.0
    - Optional: mpdf/mpdf for PDF export

Testing
-------

[](#testing)

```
# Install dependencies
composer install

# Run tests (if available)
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

MIT License - See [LICENSE](LICENSE) file for details

Author
------

[](#author)

**Amir Mahvari**

- GitHub: [@amirmahvari](https://github.com/amirmahvari)

Support
-------

[](#support)

For issues, questions, or suggestions, please open an issue on GitHub.

---

Made with ❤️ for WordPress &amp; PHP developers

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance46

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/31b5966276b25badec007de6710343c5e6064a9e3fb06ce6759c1d75da8c0b17?d=identicon)[amirmahvari](/maintainers/amirmahvari)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/amirmahvari-wb-utilities/health.svg)

```
[![Health](https://phpackages.com/badges/amirmahvari-wb-utilities/health.svg)](https://phpackages.com/packages/amirmahvari-wb-utilities)
```

PHPackages © 2026

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