fort/php

PHP Global helpers

5.8 2023-10-28 01:02 UTC

This package is auto-updated.

Last update: 2024-04-21 11:16:34 UTC


README

Build Status Packagist Version (custom server) Packagist Downloads (custom server) GitHub

Installation

install with composer

  composer require fort/php

Add the below codes in your index.php or entry point of your application;

<?php
require_once __DIR__ . "/vendor/autoload.php";
\Dotenv\Dotenv::createImmutable(__DIR__)->load();
 

Available PHP Functions

Table of Content

Database

To start using the database support, you must create a .env file just in the root directory of your project and set your database credentials like below

DB_DATABASE=fort_project
DB_PORT=3306
DB_HOST=localhost
DB_USER=sam
DB_PASSWORD=sammyabc

Test DB connection

Test if the databases was successfully connected

<?php
use Fort\PHP\Support\DB;

DB::connect();

// PDO Object: connected

Insert Record

Insert or create a new record in your database

<?php
use Fort\PHP\Support\DB;
use Carbon\Carbon;

DB::insert('users', [
 'name'=> 'Phil Everette',
 'email'=> 'pever@example.com',
 'phone'=> '0205550368',
 'created_at'=> Carbon::now() // fort/php already ships with carbon
]);

// @return (bool) true, false otherwise

Update Record

Update a specific record in your database.

<?php
use Fort\PHP\Support\DB;
use Carbon\Carbon;

DB::update('users', 1, [
 'name'=> 'Sam Everette',
 'email'=> 'pever@example.com',
 'phone'=> '0205550368',
 'created_at'=> Carbon::now()  
]);

// 1 is the id of the record to update
// @return (bool) true, false otherwise

Transactions

Start database transactions.

<?php
use Fort\PHP\Support\DB;
 

public function createInvoice()
{
  try
   {
  DB::beginTransaction();
  //start some database queries
  DB::commit();
  // commit the queries
 }
 
 catch (Exception $exception)
 {
   DB::rollBack();
  // rollback the transaction in case of error
 }
}

Queries

Run queries to your database.

<?php
use Fort\PHP\Support\DB;

$unpaidOrders = DB::table('orders')
  ->where('payment_status', '=', 'unpaid')
  ->orderBy('id', 'desc')
  ->get();
  
foreach ($unpaidOrders as $item){
  echo  $item['amount'];
}

Raw Queries

<?php
use Fort\PHP\Support\DB;

$items = DB::rawQuery("SELECT users.id FROM users, 
 INNER JOIN orders ON users.id = orders.user_id")->get();
  
foreach ($items as $item){
 // echo ... ;
}

Select

<?php
use Fort\PHP\Support\DB;

$adult = DB::table('users')
  ->select(['name', 'age'])
  ->where('age', '>', 18)
  ->orderBy('id', 'desc')
  ->get();
  
foreach ($adult as $individual){
  echo  $individual['age'];
}

All

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->all();
// @returns all invoices

First

<?php
use Fort\PHP\Support\DB;

DB::table('users')->where('email', '=','sam@example.com')->first();
// @returns the record in the query set

Where

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->where('amount_paid', '<', 1)->get();

OrWhere

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->where('amount_paid', '<', 1)
  ->orWhere('amount_paid', '=', false)
  ->get();

Sum

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->sum('amount_paid');
// @returns (int|float) a sum of the specified column

Count

<?php
use Fort\PHP\Support\DB;

  DB::table('orders')->count();
  // @returns total number of orders

Max

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->max('amount');
// @returns (int|float) the highest number in the column

Min

<?php
use Fort\PHP\Support\DB;

DB::table('invoices')->min('amount');
// @returns (int|float) the smallest number in the column

Http Requests

Post Request

<?php
 use Fort\PHP\Support\Http;
 
 Http::post('https://api.velstack.com/send',[$data],
            ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"];

Get Request

<?php
 use Fort\PHP\Support\Http;
 
 Http::get('https://api.velstack.com/resource', 
            ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],
            ['timeout'=> 20, 'return_transfer'=> true, 'maxredirs'=> 10, 'encoding'=> ""]);

Put/Patch Request

<?php
 use Fort\PHP\Support\Http;
 
 Http::put('https://api.velstack.com/resource', [$data],
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],

Delete Request

<?php
 use Fort\PHP\Support\Http;
 
 Http::delete('https://api.velstack.com/resource', 
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY}"],

PostMultipart Request

<?php
 use Fort\PHP\Support\Http;
 
 Http::asPostMultipart('https://api.velstack.com/send', [$data],
             ["Accept" => "application/json", "Authorization" => "Bearer API_KEY"]
             );

String Helpers

Str valueExist

<?php
use Fort\PHP\Str;

$haystack = array('FORT', 'Everette', 'Mike');
// returns true if the needle exist in case insensitive, false otherwise
Str::valueExist($haystack, 'foRT');
 // true

Str contains

<?php
use Fort\PHP\Str;

$slice = Str::contains('I was raised in Ghana', 'Ghana');
// 'true'

Str containsAll

<?php
use Fort\PHP\Str;

$string = Str::containsAll('My dad is from UK but i live in the US', ['UK', 'US']);

// 'true'

Str after

<?php
use Fort\PHP\Str;

$slice = Str::after('His name is fort', 'His name');
// ' is fort'

Str afterLast

<?php
use Fort\PHP\Str;

$slice = Str::afterLast('app\Http\Controllers\Controller', '\\');
// 'Controller'

Str before

<?php
use Fort\PHP\Str;

$slice = Str::before('He is married', 'married');
// 'He is'

Str beforeLast

<?php
use Fort\PHP\Str;

$slice = Str::beforeLast('He is married', 'is');
// 'He'

Str between

<?php
use Fort\PHP\Str;

$slice = Str::between('He was born in March', 'He', 'March');
// 'was born in'

Str replace

<?php
use Fort\PHP\Str;


$string = 'Transporter is a brilliant !';

$replaced = Str::replace('brilliant', 'genius', $string);

// Transporter is a genius !

Str charAt

<?php
use Fort\PHP\Str;


$string = 'Transporter !';

$char = Str::charAt($string, 3);

// t

Str endsWith

<?php
use Fort\PHP\Str;


$string = 'Everette is 1 year old';

$string = Str::endsWith($string, 'old');

// true

Str finish

<?php
use Fort\PHP\Str;


$string = 'Everette is 1 year old';

$string = Str::finish($string, '!');

// Everette is 1 year old!

Str is

The Str::is method determines if a given string matches a given pattern. Asterisks may be used as wildcard values:

<?php
use Fort\PHP\Str;


$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

Str isUuid

<?php
use Fort\PHP\Str;


$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

Str length

<?php
use Fort\PHP\Str;


$isUuid = Str::length('Velstack');

// 8

Str words

<?php
use Fort\PHP\Str;

 Str::words('Though he came, he could not make it.', 3, ' >>>');

// Though he came, >>>

Str wordCount

<?php
use Fort\PHP\Str;

 Str::words('He was born in July');

// 5

Str limit

<?php
use Fort\PHP\Str;


$truncated = Str::limit('He is a good man', 4, ' ...');

// He is ...

Str padBoth

<?php
use Fort\PHP\Str;

$padded = Str::padBoth('sammy', 10, '_');

// 'sammy'

$padded = Str::padBoth('James', 10);

// '  sammy   '

Str padLeft

<?php
use Fort\PHP\Str;


$padded = Str::padLeft('sammy', 6, '@');

// @sammy'

$padded = Str::padLeft('sammy', 6);

// '    sammy'

Str padRight

<?php
use Fort\PHP\Str;

$padded = Str::padRight('sammy', 10, '-');

// 'sammy-----'

$padded = Str::padRight('sammy', 10);

// 'sammy     '

Str random

<?php
use Fort\PHP\Str;

$random = Str::random(5);

// 3Cewm

Str uuid

<?php
use Fort\PHP\Str;

$output = Str::uuid();

// a0a2a2d2-0b87-4a18-83f2-2529882be2de

Str isAscii

<?php
use Fort\PHP\Str;

$isAscii = Str::isAscii('Accra');

// true

$isAscii = Str::isAscii('ü');

// false

Str isUuid

<?php
use Fort\PHP\Str;

$string = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$string = Str::isUuid('Accra');

// false

Str upper

<?php
use Fort\PHP\Str;


$converted = Str::upper('fort');

// FORT

Str lower

<?php
use Fort\PHP\Str;


$converted = Str::lower('FORT');

// fort

Str title

<?php
use Fort\PHP\Str;


$converted = Str::title('how to make money from home');

// How To Make Money From Home

Str slug

<?php
use Fort\PHP\Str;


$converted = Str::slug('how to make money from home','-');

// How-To-Make-Money-From-Home

Str snake

<?php
use Fort\PHP\Str;


$output = Str::snake('FootBall', '_');

// Foot_Ball

Str studly

<?php
use Fort\PHP\Str;

$output = Str::studly('foo_bar');

// FooBar

Str kebab

<?php
use Fort\PHP\Str;


$output = Str::kebab('fooBar');

// foo-bar

Str mask

<?php
use Fort\PHP\Str;


$string = Str::mask('samuelfort@example.com', '*', -15, 3);

// sam***@example.com

Str start

The Str::start method adds a single instance of the given value to a string if it does not already start with that value:

<?php
use Fort\PHP\Str;

$adjusted = Str::start('sammy_fort', '@');

// @sammy_fort

$adjusted = Str::start('@fortameyaw', '@');

// @fortameyaw

Str reverse

<?php
use Fort\PHP\Str;

$reversed = Str::reverse('Hello');

// olleH

Str substr

<?php
use Fort\PHP\Str;


$converted = Str::substr('The Symfony PHP Framework', 4, 7);

// Laravel

Str substrCount

<?php
use Fort\PHP\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str substrReplace

<?php
use Fort\PHP\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str replaceFirst

<?php
use Fort\PHP\Str;

$string  = 'He is lazy';

$output = Str::replaceFirst('He', 'Tom', $string);

// Tom is lazy

Str replaceLast

<?php
use Fort\PHP\Str;

$string  = 'Kwaku is a handsome boy';

$output = Str::replaceLast('a', 'the', $string);

// Kwaku is the handsome boy

Str lcfirst

<?php
use Fort\PHP\Str;

$output = Str::lcfirst('Handsome');

// handsome

Str ucfirst

<?php
use Fort\PHP\Str;

$output = Str::ucfirst('beautiful');

// Beautiful

Array Helpers

Arr Maximum

<?php
 use Fort\PHP\Arr;
 
$array = ['Transporter'=> 3, 'Phil'=> 0, 'Ever'=> 1];

print_r(Arr::maximum($array));

// Transporter

Arr Minimum

<?php
 use Fort\PHP\Arr;
 
$array = ['Transporter'=> 3, 'Phil'=> 1, 'Ever'=> 0];

print_r(Arr::minimum($array));

// Ever

Arr valueExist

Checks in an array if the needle exist in the array in case-insensitive manner. @returns true if the needle exist, false otherwise.

<?php
 use Fort\PHP\Arr;
 
$array = ['Transporter', 'Phil', 'Ever'];

 print_r(Arr::valueExist($array, 'FORT'));

// true

Arr accessible

<?php
 use Fort\PHP\Arr;
 
$array = ['Transporter' => 1, 'Phil'=> 2, 'Ever' => 3];

 print_r(Arr::accessible($array));

// true

$array = "fort";

 print_r(Arr::accessible($array));

// false

Arr whereNotNull

<?php
 use Fort\PHP\Arr;
 
$array = [0, null];
 
$filtered = Arr::whereNotNull($array);
 
// [0 => 0]

Arr where

<?php
 use Fort\PHP\Arr;
 
$array = [100, '200', '300', '400', '500'];
 
$filtered = Arr::where($array, function ($value, $key) {
    return is_numeric($value);
});
 
// [0 => '100']

Arr first

<?php
 use Fort\PHP\Arr;
 
$array = [1, 15, 35];
 
$first = Arr::first($array, function ($value, $key) {
    return $value >= 20;
});
 
// 35

Arr last

<?php
 use Fort\PHP\Arr;
 
$array = [1, 15, 35, 40];
 
$first = Arr::last($array, function ($value, $key) {
    return $value >= 40;
});
 
// 40
 
 

Arr wrap

<?php
 use Fort\PHP\Arr;
 
$string = 'PHP is fun';
 
$array = Arr::wrap($string);
 
// ['PHP is fun']

Arr add

The Arr::shuffle method randomly shuffles the items in the array:

<?php
 use Fort\PHP\Arr;
 
$array = Arr::add(['name' => 'Desk'], 'price', 100);
 
// ['name' => 'Desk', 'price' => 100]
 
$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
 
// ['name' => 'Desk', 'price' => 100]

Arr set

<?php
 use Fort\PHP\Arr;
 
$array = ['orders' => ['desk' => ['price' => 100]]];
 
Arr::set($array, 'orders.desk.price', 200);
 
// ['orders' => ['desk' => ['price' => 200]]]

Arr shuffle

The Arr::shuffle method randomly shuffles the items in the array:

<?php
 use Fort\PHP\Arr;
 
$array = Arr::shuffle([1, 2, 3, 4, 5]);
 
// [3, 2, 5, 1, 4] - (generated randomly)

Arr collapse

<?php
 use Fort\PHP\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
 
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Arr divide

The Arr::divide method returns two arrays: one containing the keys and the other containing the values of the given array:

<?php
 use Fort\PHP\Arr;
 
[$keys, $values] = Arr::divide(['name' => 'Desk']);
 
// $keys: ['name']
 
// $values: ['Desk']

Arr except

<?php
 use Fort\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
 
$filtered = Arr::except($array, ['price']);
 
// ['name' => 'Desk']

Arr exists

<?php
 use Fort\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
$array = ['name' => 'John Doe', 'age' => 17];
 
$exists = Arr::exists($array, 'name');
 
// true

$exists = Arr::exists($array, 'salary');
 
// false

Arr flatten

<?php
 use Fort\PHP\Arr;
 
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
 
$flattened = Arr::flatten($array);
 
// ['Joe', 'PHP', 'Ruby']
 
// false

Arr forget

<?php
 use Fort\PHP\Arr;
 
$array = ['products' => ['desk' => ['price' => 100]]];
 
Arr::forget($array, 'products.desk');
 
// ['products' => []]

Arr get

<?php
 use Fort\PHP\Arr;
 
$array = ['products' => ['desk' => ['price' => 100]]];
 
$price = Arr::get($array, 'products.desk.price');
 
// 100

Arr has

<?php
 use Fort\PHP\Arr;
 
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
 
$contains = Arr::has($array, 'product.name');
 
// true
 
$contains = Arr::has($array, ['product.price', 'product.discount']);
 
// false

Arr hasAny

<?php
 use Fort\PHP\Arr;
 
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
 
$contains = Arr::hasAny($array, 'product.name');
 
// true
 
$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
 
// true
 
$contains = Arr::hasAny($array, ['category', 'product.discount']);
 
// false

Arr isAssoc

<?php
 use Fort\PHP\Arr;
 
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
 
// true
 
$isAssoc = Arr::isAssoc([1, 2, 3]);
 
// false

Arr prepend

<?php
 use Fort\PHP\Arr;
 
$array = ['one', 'two', 'three', 'four'];
 
$array = Arr::prepend($array, 'zero');
 
// ['zero', 'one', 'two', 'three', 'four']

$array = ['price' => 100];
 
$array = Arr::prepend($array, 'Desk', 'name');
 
// ['name' => 'Desk', 'price' => 100]

Arr pluck

<?php
 use Fort\PHP\Arr;
 
$array = [
    ['product' => ['id' => 1, 'name' => 'Drink']],
    ['product' => ['id' => 2, 'name' => 'Wheat']],
];
 
$names = Arr::pluck($array, 'product.name');
 
// ['Drink', 'Wheat']

Arr only

<?php
 use Fort\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
 
$slice = Arr::only($array, ['name', 'price']);
 
// ['name' => 'Desk', 'price' => 100]

Arr pull

<?php
 use Fort\PHP\Arr;
 
$array = ['name' => 'Desk', 'price' => 100];
 
$name = Arr::pull($array, 'name');
 
// $name: Desk
 
// $array: ['price' => 100]

Arr query

<?php
 use Fort\PHP\Arr;
 
$array = [
    'name' => 'Mike',
    'order' => [
        'column' => 'created_at',
        'direction' => 'desc'
    ]
];
 
 $q = Arr::query($array);
 
// name=Mike&order[column]=created_at&order[direction]=desc

Arr random

<?php
 use Fort\PHP\Arr;
 
$array = [1, 2, 3, 4, 5];
 
$random = Arr::random($array);
 
// 4 - (retrieved randomly)

SMS

To start using the SMS support, you must set the following variables in your .env file. The SMS_DRIVER can only be set to velstack or vonage. These are the supported drivers.

SMS_DRIVER=velstack
SMS_API_KEY=sk_test__
SMS_SECRET_KEY=
SMS_SENDER_ID=BUSINESS

Send SMS

<?php
 use Fort\PHP\Support\SMS;
 
 return SMS::send('+233205550368', 'Hello, API messaging is just awesome');

Math Helpers

Percentage

<?php
 use Fort\PHP\Math;
 
 Math::percentage(1.5, 200);
 // 3

Exponential

<?php
 use Fort\PHP\Math;
 
 Math::expo(2, 2);
 // 4

SquareRoot

<?php
 use Fort\PHP\Math;
 
 Math::sqrRoot(20);
  // 4.4721359549996

Summation

<?php
 use Fort\PHP\Math;
 
 Math::sum(11, 11);
 // 22

Subtraction

<?php
 use Fort\PHP\Math;
 
 Math::sub(10, 11);
 // -1

Division

<?php
 use Fort\PHP\Math;
 
 Math::div(19, 5);
 // 3.8

Multiplication

<?php
 use Fort\PHP\Math;
 
 Math::mul(21, 8);
 // 168

Maximum

<?php
 use Fort\PHP\Math;
 
 Math::max(2, 6, 4);
 // 6

Minimum

<?php
 use Fort\PHP\Math;
 
 Math::min(2, 6, 4);
 // 2

Make sure model uses the DateFilters trait

 

namespace App\Models;

use Fort\Illuminate\Support\Eloquent\DateFilters;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    use HasFactory, DateFilters;
     

    protected $table = 'invoices';

     protected $fillable = [
        'user_id',
        'invoice_id',
        'customer',
        'shipping' ,
    ];

      
}

Once the DateFilters has been implemented in your model, you may access them in your controller like below

 
namespace App\Http\Controllers\Subscription;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
 

class InvoiceController extends Controller
{
 

    public function getTodayInvoices()
    {

        return Invoice::today()->get();
        
        // all invoices created today
    }
    
    public function yesterday()
    {

        return Invoice::yesterday()->sum('amount');
        // sums yesterday invoices amount
    }
    
     public function week()
     {

        return Invoice::Last7Days()->get();
        // returns invoices of the last 7 days
    }
    
    
       public function two_weeks()
     {

        return Invoice::QuarterToDate()->get();
        // returns all invoices from last two weeks
    }
    
     public function this_month()
     {

        return Invoice::MonthToDate()->sum('amount');
        // returns invoices from the start of the current month 
    }
    
    public function last30days()
     {

        return Invoice::Last30Days()->get();
         // returns invoices created in the last 30 days.
     }
    
   
    
    public function this_year()
     {

        return Invoice::YearToDate()->get();
        // returns all invoices from the start of the year
    }
    
    
      public function last_year()
     {

        return Invoice::LastYear()->get();
        // returns all invoices from last year
    }
    
    
       public function last_quater()
     {

        return Invoice::LastQuarter()->get();
        // returns all invoices from last 3 months
    }  
}