Smart File System - Use SmartFileInfo with useful methods that you need everyday

Overview

Smart File System

Downloads total

Install

composer require symplify/smart-file-system

Use

Does SplFileInfo exist?

The SplFileInfo::getRealPath() method returns absolute path to the file... or FALSE, if the file doesn't exist. This default PHP behavior forces you to check all getRealPath() calls:

$fileInfo = new SplFileInfo('non_existing_file.txt');

if ($fileInfo->getRealPath() === false) {
    // damn, the files doesn't exist
    // throw exception or whatever
    // everytime!
}

$fileRealPath = $fileInfo->getRealPath();

While this has a reason - e.g. to be sure the file was not deleted since the construction, we actually have to call the method to find out the file was removed. Another annoyance is to tell this to static analyzers.

In reality, it's very rare to work with file that was existing a while ago, but now is gone, without us doing it on purpose. We usually use SplFileInfo to modify files or work with their paths.

What if:

  • we could remove this problem and make sure getRealPath() method always returns string?
  • get an exception of non-existing file on SplFileInfo creation?

Introducing SmartFileInfo

$fileInfo = new Symplify\SmartFileSystem\SmartFileInfo('non_existing_file.txt');
// throws Symplify\SmartFileSystem\Exception\FileNotFoundException

This class also bring new useful methods:

getBasenameWithoutSuffix(); // "ExistingFile" echo $smartFileInfo->getRelativeFilePath(); // "src/ExistingFile.php" echo $smartFileInfo->getRelativeDirectoryPath(); // "src" echo $smartFileInfo->getRelativeFilePathFromDirectory('/var'); // "www/src/ExistingFile.php"">
// current directory (cwd()) is "/var/www"
$smartFileInfo = new Symplify\SmartFileSystem\SmartFileInfo('/var/www/src/ExistingFile.php');

echo $smartFileInfo->getBasenameWithoutSuffix();
// "ExistingFile"

echo $smartFileInfo->getRelativeFilePath();
// "src/ExistingFile.php"

echo $smartFileInfo->getRelativeDirectoryPath();
// "src"

echo $smartFileInfo->getRelativeFilePathFromDirectory('/var');
// "www/src/ExistingFile.php"

It also fixes WTF behavior of Symfony\Component\Finder\SplFileInfo. Which one? When you run e.g. vendor/bin/ecs check src and use Finder, the getRelativeFilePath() in Symfony now returns all the relative paths to src. Which is useless, mainly with multiple dirs like: vendor/bin/ecs check src tests both containing file Post.php.

$smartFileInfo = new Symplify\SmartFileSystem\SmartFileInfo('/var/www/src/Post.php');

echo $smartFileInfo->getRelativeFilePathFromCwd();
// "src/Post.php"

File name Matching

Last but not least, matching a file comes useful in excluding files (typical for tools like ECS, PHPStan, Psalm, Rector, PHP CS Fixer or PHP_CodeSniffer):

$smartFileInfo = new Symplify\SmartFileSystem\SmartFileInfo('/var/www/src/PostRepository.php');

echo $smartFileInfo->endsWith('Repository.php');
// true

echo $smartFileInfo->doesFnmatch('*Repo*');
// true

Smart FileSystem - Just like Symfony, just Better

New method - readFile() (to read files):

$smartFileSystem = new Symplify\SmartFileSystem\SmartFileSystem();
$fileContent = $smartFileSystem->readFile(__DIR__ . '/SomeFile.php');
// if you plan to use SmartFileInfo, use this
$smartFileInfo = $smartFileSystem->readFileToSmartFileInfo(__DIR__ . '/SomeFile.php');

Sanitizer various files to SmartFileInfo[]

Do you have multiple file inputs that can mix-up?

$files = [new SplFileInfo('someFile.php')];

$files = [new Symfony\Component\Finder\SplFileInfo('someFile.php', 'someFile', '')];

// or
$files = (new Symfony\Component\Finder\Finder())->files();

// or
$files = Nette\Utils\Finder::findFiles('*');

// or
$files = ['someFile.php'];

Later, you wan to actually work with the files:

foreach ($files as $file) {
    // what methods do we have here
    // what kind of object?
    // is it even object or a string?
    $file->...
}

Use sanitized files, that have united format you can rely on:

use Symplify\SmartFileSystem\Finder\FinderSanitizer;

$finderSanitizer = new FinderSanitizer();
$smartFileInfos = $finderSanitizer->sanitize($files);

// always array of Symplify\SmartFileSystem\SmartFileInfo
var_dump($smartFileInfos);

Report Issues

In case you are experiencing a bug or want to request a new feature head over to the Symplify monorepo issue tracker

Contribute

The sources of this package are contained in the Symplify monorepo. We welcome contributions for this package on symplify/symplify.

You might also like...
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

PHP 7+ Payment processing library. It offers everything you need to work with payments: Credit card & offsite purchasing, subscriptions, payouts etc. - provided by Forma-Pro

Supporting Payum Payum is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our

This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.

This library provides a collection of native enum utilities (traits) which you almost always need in every PHP project.

The last validation library you will ever need!
The last validation library you will ever need!

Mighty The last validation library you will ever need! Table of Contents Installation About Mighty Quickstart Mighty Validation Expression Language Ex

A useful PocketMine-MP plugin that allows you to create crates in-game!

ComplexCrates A useful PocketMine-MP plugin that allows you to create crates in-game! Commands Main command: /crate Sub commands: create

This Kirby V3 Plugin brings snippets and blueprints together in one place. It includes useful tools that completely changing the way you work with Kirby: Fast and well organized.
This Kirby V3 Plugin brings snippets and blueprints together in one place. It includes useful tools that completely changing the way you work with Kirby: Fast and well organized.

Kirby Components Overview Do you love to make awesome projects with Kirby CMS? Do you also find it difficult to switch between snippets and blueprints

Track your farming and pool performance on the Binance Smart Chain

farm.army - Frontend Track your farming and pool performance on the Binance Smart Chain. Tech Stack PHP 8 + Symfony node.js + npm (Webpack, Symfony en

A proof-of-concept parser for the SMART Health Cards format.

SMART Health Cards parser A proof-of-concept parser for the SMART Health Cards format. This is not intended for production use. I just hacked this tog

A smart way of seeding tables in Laravel

SmartSeeder for Laravel For Laravel 5, please use the 5.0 branch! For Laravel 4, please use the 4.2 branch! Seeding as it is currently done in Laravel

Owner
Easy Coding Standard, Static Site Generator, Package Builder utils on PHP 8.0 and Symfony 5.4
null
An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods.

OrchidTables An opinionated extension package for Laravel Orchid to extend its table handling capabilities, and some further useful helper methods. In

null 25 Dec 22, 2022
Collection of PHP functions, mini classes and snippets for everyday developer's routine life

JBZoo / Utils Collection of PHP functions, mini classes and snippets for everyday developer's routine life. Install composer require jbzoo/utils Usage

JBZoo Toolbox 776 Jun 2, 2022
A super simple, clean and pretty error handler that replace the default error handler of PHP. You need only include this file!

php-custom-error-handler A super simple, clean and pretty error handler that replace the default error handler of PHP. You need just include only this

null 6 Nov 7, 2022
Do you want CronJob to follow the solar date?You need this package to solve this problem.

Shamsic Maybe it happened to you that you wanted to use CronJob in your project and you realized that you cannot manage the exact dates that are in th

Amin Ghaninia 5 Jul 19, 2022
This packages enables the ability to serve file streams in a smart way

A blade component for easy image manipulation Want to serve private hosted images without the need to code your own logic ? Want to resize your images

Dieter Coopman 205 Dec 19, 2022
salah eddine bendyab 18 Aug 17, 2021
Starless Sky is a network protocol for secure identities, providing the use of assymetric identities, public information, end-to-end messaging and smart contracts

Descentralized network protocol providing smart identity over an secure layer. What is the Starless Sky Protocol? Starless Sky is a network protocol f

Starless Sky Protocol 3 Jun 19, 2022
Re-skinning BotCloaker enables you to add a SMART button at the end of all posts on your blog.

Re-skinning BotCloaker Wordpress Plugin Re-skinning BotCloaker enables you to add a SMART button at the end of all posts on your blog. Re-skinning Bot

Mohammed cha 120 Nov 11, 2022
Open Source Smart Meter with focus on privacy - you remain the master of your data.

volkszaehler.org volkszaehler.org is a free smart meter implementation with focus on data privacy. Demo demo.volkszaehler.org Quickstart The easiest w

volkszaehler.org project 176 Jan 4, 2023