Convert Figma logo to code with AI

thecodingmachine logosafe

All PHP functions, rewritten to throw exceptions instead of returning false

2,337
140
2,337
93

Top Related Projects

9,433

Doctrine Database Abstraction Layer

4,825

The lightweight PHP database framework to accelerate the development.

2,656

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!

2,007

A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

[READ ONLY] Subtree split of the Illuminate Database component (see laravel/framework)

Quick Overview

Safe is a PHP library that provides type-safe wrappers for PHP's native functions. It aims to improve type safety and reduce common errors by offering strict type checking and consistent return types. Safe functions throw exceptions instead of returning false or generating warnings, making error handling more predictable and robust.

Pros

  • Improves type safety in PHP applications
  • Provides consistent error handling through exceptions
  • Offers a drop-in replacement for native PHP functions
  • Enhances code reliability and reduces runtime errors

Cons

  • May introduce a slight performance overhead
  • Requires adapting to a new error handling paradigm
  • Not all PHP functions are covered (though most common ones are)
  • Might conflict with other libraries or frameworks that modify PHP's native functions

Code Examples

  1. Using Safe for file operations:
use function Safe\file_get_contents;

try {
    $content = file_get_contents('non_existent_file.txt');
} catch (\Safe\Exceptions\FilesystemException $e) {
    echo "File not found: " . $e->getMessage();
}
  1. Handling JSON encoding with Safe:
use function Safe\json_encode;

$data = ['key' => 'value'];
try {
    $json = json_encode($data, JSON_THROW_ON_ERROR);
} catch (\Safe\Exceptions\JsonException $e) {
    echo "JSON encoding failed: " . $e->getMessage();
}
  1. Database operations with Safe:
use function Safe\mysqli_query;

$mysqli = new mysqli("localhost", "user", "password", "database");
try {
    $result = mysqli_query($mysqli, "SELECT * FROM users");
} catch (\Safe\Exceptions\MysqliException $e) {
    echo "Query failed: " . $e->getMessage();
}

Getting Started

To start using Safe in your PHP project:

  1. Install the library using Composer:

    composer require thecodingmachine/safe
    
  2. Use the Safe functions in your code:

    use function Safe\file_get_contents;
    use function Safe\json_decode;
    
    $content = file_get_contents('config.json');
    $config = json_decode($content, true);
    
  3. Optionally, you can use the global functions by adding this to your composer.json:

    {
      "autoload": {
        "files": ["vendor/thecodingmachine/safe/generated/php_polyfill.php"]
      }
    }
    

After adding this, run composer dump-autoload to regenerate the autoloader.

Competitor Comparisons

9,433

Doctrine Database Abstraction Layer

Pros of DBAL

  • More comprehensive database abstraction layer, supporting multiple database systems
  • Extensive query building and result set handling capabilities
  • Mature project with a large community and extensive documentation

Cons of DBAL

  • Heavier and more complex, potentially overkill for simple database operations
  • Steeper learning curve compared to Safe's straightforward approach
  • May introduce unnecessary overhead for basic SQL queries

Code Comparison

Safe (simple query execution):

$result = Safe\mysqli_query($connection, "SELECT * FROM users");

DBAL (query builder):

$queryBuilder = $connection->createQueryBuilder();
$result = $queryBuilder
    ->select('*')
    ->from('users')
    ->execute();

Safe focuses on providing safer alternatives to PHP functions, including database operations, while DBAL offers a more comprehensive database abstraction layer. Safe is lightweight and easy to use for basic operations, whereas DBAL provides more advanced features at the cost of increased complexity.

4,825

The lightweight PHP database framework to accelerate the development.

Pros of Medoo

  • Lightweight and simple to use, with a focus on ease of implementation
  • Supports multiple database types (MySQL, MSSQL, SQLite, etc.) with a unified API
  • Extensive documentation and examples available

Cons of Medoo

  • Less robust type safety compared to Safe
  • Limited advanced features and customization options
  • May not be as suitable for complex, large-scale applications

Code Comparison

Medoo:

$data = $database->select("table", [
    "column1",
    "column2"
], [
    "id" => 1
]);

Safe:

$row = $connection->select('table')
    ->columns('column1', 'column2')
    ->where('id = :id')
    ->params(['id' => 1])
    ->fetch();

Key Differences

  • Safe focuses on type safety and strict coding practices, while Medoo prioritizes simplicity and ease of use
  • Safe provides more advanced features for complex queries and database operations
  • Medoo offers broader database support out of the box
  • Safe's query builder is more verbose but provides better control and readability
  • Medoo's syntax is more concise, making it easier for beginners to get started

Both libraries have their strengths and are suitable for different use cases. Safe is better for large, complex projects requiring strict type safety, while Medoo is ideal for smaller projects or rapid prototyping.

2,656

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!

Pros of Fat-Free

  • Lightweight and fast, with a small footprint
  • Simple and easy to learn, with a gentle learning curve
  • Flexible routing system with support for RESTful URLs

Cons of Fat-Free

  • Less robust type-checking and safety features
  • Smaller community and fewer extensions/plugins
  • Limited built-in security features compared to Safe

Code Comparison

Fat-Free:

$f3 = Base::instance();
$f3->route('GET /@language/@page', function($f3, $params) {
    echo "Language: {$params['language']}, Page: {$params['page']}";
});
$f3->run();

Safe:

use Safe\Exceptions\FilesystemException;

try {
    $content = Safe\file_get_contents('file.txt');
} catch (FilesystemException $e) {
    echo "Error reading file: " . $e->getMessage();
}

Fat-Free is a lightweight PHP framework focused on simplicity and speed, while Safe is a set of core PHP function wrappers that throw exceptions instead of returning false or null on errors. Fat-Free is better suited for rapid development of small to medium-sized applications, while Safe is more focused on improving error handling and type safety in PHP projects.

2,007

A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Pros of idiorm

  • Lightweight and simple ORM with minimal setup required
  • Supports multiple database types (MySQL, SQLite, PostgreSQL)
  • Easy to learn and use for beginners

Cons of idiorm

  • Lacks advanced features like migrations and schema management
  • Not actively maintained (last commit in 2018)
  • Limited support for complex queries and relationships

Code Comparison

idiorm:

ORM::for_table('user')
    ->where('name', 'John')
    ->find_one();

safe:

$user = $connection->select('user')
    ->where('name = :name')
    ->setParameter('name', 'John')
    ->fetchOne();

Key Differences

  • safe focuses on type safety and uses a fluent interface for query building
  • idiorm provides a simpler API but with less type checking
  • safe is actively maintained and offers more advanced features
  • idiorm is more suitable for small projects or quick prototypes

Conclusion

While idiorm offers simplicity and ease of use, safe provides better type safety and more advanced features. The choice between the two depends on project requirements and developer preferences.

[READ ONLY] Subtree split of the Illuminate Database component (see laravel/framework)

Pros of Database

  • More comprehensive database functionality, including query building, migrations, and ORM features
  • Part of the larger Laravel ecosystem, offering seamless integration with other Laravel components
  • Extensive documentation and community support

Cons of Database

  • Heavier and more complex, potentially overkill for simple projects
  • Primarily designed for Laravel, may require additional setup for standalone use
  • Steeper learning curve for developers new to Laravel or ORM concepts

Code Comparison

Safe (PHP type-safe operations):

$result = Safe\file_get_contents('file.txt');
$json = Safe\json_decode($result, true);

Database (Query building):

$users = DB::table('users')
            ->where('votes', '>', 100)
            ->get();

Summary

Safe focuses on providing type-safe wrappers for PHP functions, enhancing code reliability. Database, on the other hand, offers a full-featured database toolkit with ORM capabilities. Safe is lightweight and easy to integrate into any PHP project, while Database provides more powerful features but is primarily designed for use within the Laravel framework. The choice between the two depends on the project's requirements and the developer's familiarity with Laravel.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Latest Stable Version Total Downloads Latest Unstable Version License Build Status Continuous Integration codecov

Safe PHP

A set of core PHP functions rewritten to throw exceptions instead of returning false when an error is encountered.

The problem

Most PHP core functions were written before exception handling was added to the language. Therefore, most PHP functions do not throw exceptions. Instead, they return false in case of error.

But most of us are too lazy to check explicitly for every single return of every core PHP function.

// This code is incorrect. Twice.
// "file_get_contents" can return false if the file does not exist
// "json_decode" can return false if the file content is not valid JSON
$content = file_get_contents('foobar.json');
$foobar = json_decode($content);

The correct version of this code would be:

$content = file_get_contents('foobar.json');
if ($content === false) {
    throw new FileLoadingException('Could not load file foobar.json');
}
$foobar = json_decode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new FileLoadingException('foobar.json does not contain valid JSON: '.json_last_error_msg());
}

Obviously, while this snippet is correct, it is less easy to read.

The solution

Enter thecodingmachine/safe aka Safe-PHP.

Safe-PHP redeclares all core PHP functions. The new PHP functions act exactly as the old ones, except they throw exceptions properly when an error is encountered. The "safe" functions have the same name as the core PHP functions, except they are in the Safe namespace.

use function Safe\file_get_contents;
use function Safe\json_decode;

// This code is both safe and simple!
$content = file_get_contents('foobar.json');
$foobar = json_decode($content);

All PHP functions that can return false on error are part of Safe. In addition, Safe also provide 2 'Safe' classes: Safe\DateTime and Safe\DateTimeImmutable whose methods will throw exceptions instead of returning false.

PHPStan integration

Yeah... but I must explicitly think about importing the "safe" variant of the function, for each and every file of my application. I'm sure I will forget some "use function" statements!

Fear not! thecodingmachine/safe comes with a PHPStan rule.

Never heard of PHPStan before? Check it out, it's an amazing code analyzer for PHP.

Simply install the Safe rule in your PHPStan setup (explained in the "Installation" section) and PHPStan will let you know each time you are using an "unsafe" function.

The code below will trigger this warning:

$content = file_get_contents('foobar.json');

Function file_get_contents is unsafe to use. It can return FALSE instead of throwing an exception. Please add 'use function Safe\file_get_contents;' at the beginning of the file to use the variant provided by the 'thecodingmachine/safe' library.

Installation

Use composer to install Safe-PHP:

$ composer require thecodingmachine/safe

Highly recommended: install PHPStan and PHPStan extension:

$ composer require --dev thecodingmachine/phpstan-safe-rule

Now, edit your phpstan.neon file and add these rules:

includes:
    - vendor/thecodingmachine/phpstan-safe-rule/phpstan-safe-rule.neon

Automated refactoring

You have a large legacy codebase and want to use "Safe-PHP" functions throughout your project? PHPStan will help you find these functions but changing the namespace of the functions one function at a time might be a tedious task.

Fortunately, Safe comes bundled with a "Rector" configuration file. Rector is a command-line tool that performs instant refactoring of your application.

Run

$ composer require --dev rector/rector

to install rector/rector.

Run

vendor/bin/rector process src/ --config vendor/thecodingmachine/safe/rector-migrate.php

to run rector/rector.

Note: do not forget to replace "src/" with the path to your source directory.

Important: the refactoring only performs a "dumb" replacement of functions. It will not modify the way "false" return values are handled. So if your code was already performing error handling, you will have to deal with it manually.

Especially, you should look for error handling that was already performed, like:

if (!mkdir($dirPath)) {
    // Do something on error
}

This code will be refactored by Rector to:

if (!\Safe\mkdir($dirPath)) {
    // Do something on error
}

You should then (manually) refactor it to:

try {
    \Safe\mkdir($dirPath));
} catch (\Safe\FilesystemException $e) {
    // Do something on error
}

Performance impact

Safe is loading 1000+ functions from ~85 files on each request. Yet, the performance impact of this loading is quite low.

In case you worry, using Safe will "cost" you ~700µs on each request. The performance section contains more information regarding the way we tested the performance impact of Safe.

Learn more

Read the release article on TheCodingMachine's blog if you want to learn more about what triggered the development of Safe-PHP.

Contributing

The files that contain all the functions are auto-generated from the PHP doc. Read the CONTRIBUTING.md file to learn how to regenerate these files and to contribute to this library.