PHP code example of chiiya / laravel-utilities

1. Go to this page and download the library: Download chiiya/laravel-utilities library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chiiya / laravel-utilities example snippets


return [
    /*
    |--------------------------------------------------------------------------
    | Temporary path
    |--------------------------------------------------------------------------
    | Used for downloads and unzipping files.
    */
    'tmp_path' => storage_path('tmp'),
];

use Chiiya\Common\Commands\TimedCommand;  
  
class SendEmails extends TimedCommand
{
    protected $signature = 'mail:send {user}';
    
    public function handle(DripEmailer $drip)
    {
        $drip->send(User::find($this->argument('user')));
    }  

use Chiiya\Common\Mail\SetsSender;
  
class OrderShipped extends Mailables
{
    use SetsSender;

    public function build(): self
    {
        return $this
            ->subject('Order shipped')
            ->markdown('emails.orders.shipped')
            ->sender('[email protected]');
    }
}

use Chiiya\Common\Presenter\Presenter;

/** @extends Presenter<User> */  
class UserPresenter extends Presenter
{
    public function name(): string
    {
        return $this->first_name.' '.$this->last_name;
    }
}

use Chiiya\Common\Presenter\PresentableTrait;
  
class User extends Model
{
    /** @use PresentableTrait<UserPresenter> */
    use PresentableTrait;
    
    protected string $presenter = UserPresenter::class;
}

use Chiiya\Common\Repositories\AbstractRepository;

/**
 * @extends AbstractRepository<Post>
 */
class PostRepository extends AbstractRepository
{
    protected string $model = Post::class;

    /**
     * @return Collection<Post>
     */
    public function postsDiscussedYesterday()
    {
        return $this->newQuery()
            ->whereHas('comments', function (Builder $builder) {
                $builder
                    ->where('created_at', '>=', now()->subDay()->startOfDay())
                    ->where('created_at', '<=', now()->subDay()->endOfDay());
            })
            ->get();
    }

    /**
     * @inheritDoc
     */
    protected function applyFilters(Builder $builder, array $parameters): Builder
    {
        if (isset($parameters['title'])) {
            $builder->where('title', '=', $parameters['title']);
        }

        return $builder;
    }
}

// Find by primary key
$post = $repository->get(10);
// Find (first) by filters
$post = $repository->find(['title' => 'Lorem ipsum']);
// List all entities, optionally filtered
$posts = $repository->index();
$posts = $repository->index(['title' => 'Lorem ipsum']);
// Count entities, optionally filtered
$count = $repository->count();
$count = $repository->count(['title' => 'Lorem ipsum']);
// Create new entity
$post = $repository->create(['title' => 'Some title']);
// Update entity
$repository->update($post, ['title' => 'Lorem ipsum']);
// Delete entity
$repository->delete($post);

// Custom methods
$posts = $repository->postsDiscussedYesterday();

use Chiiya\Common\Services\CodeService::class;
          
class CouponService {
    public function __construct(
        private CodeService $service,
    ) {}
          
    public function generateCodes()
    {
        // Optional, import previously exported codes so that we don't generate codes that already exist
        $this->service->import(storage_path('app/exports'));
        // Generate specified amount of random codes using the given pattern and character set
        $this->service->generate(
            1_000_000,
            '####-####-####',
            CodeService::SET_NUMBERS_AND_UPPERCASE,
        );
        // Get generated codes for further processing
        $codes = $this->service->getCodes();
        // ... e.g. bulk insert $codes into database
        // Export newly generated codes into (batched) CSV files. Optionally specify the amount of codes per file
        $this->service->export(storage_path('app/exports'));
        $this->service->export(path: storage_path('app/exports'), perFile: 500_000);
    }
}

$reader = resolve(\Chiiya\Common\Services\CsvReader::class);
$reader->open('/path/to/file.csv');
foreach ($reader->rows() as $row) {
    $values = $row->toArray();
}
$reader->close();

$writer = resolve(\Chiiya\Common\Services\CsvWriter::class);
$writer->open('/path/to/file.csv');
$writer->write(['Value 1', 'Value 2']);
$writer->close();

$reader = resolve(\Chiiya\Common\Services\ExcelReader::class);
$reader->open('/path/to/file.xlsx');
foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        $values = $row->toArray();
    }
}
$reader->close();

$writer = resolve(\Chiiya\Common\Services\ExcelWriter::class);
$writer->open('/path/to/file.xlsx');
$writer->setCurrentSheetName('Sheet 1');
$writer->addHeaderRow(['Name', 'Email']);
$writer->write(['John Doe', '[email protected]']);
$writer->addSheet('Sheet 2');
$writer->write(['Value 1', 'Value 2']);
$writer->close();

$downloader = resolve(\Chiiya\Common\Services\FileDownloader::class);
$file = $downloader->download('https://example.com/path/to/file.txt');
dump($file->getPath());
$file->delete();

$zipper = resolve(\Chiiya\Common\Services\Zipper::class);
$location = $zipper->unzip('/path/to/file.zip');
bash
php artisan vendor:publish --tag="utilities-config"
bash
$ php artisan mail:send 1
> Execution time: 0.1s