• Stars
    star
    2,262
  • Rank 19,492 (Top 0.4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

react-native-boilerplate

A React Native template for building solid applications πŸ™, using JavaScript πŸ’› or Typescript πŸ’™ (you choose).
TypeScript
4,390
star
2

docker-images-php

A set of PHP Docker images
HCL
751
star
3

graphqlite

Use PHP Attributes/Annotations to declare your GraphQL API
MDX
535
star
4

phpstan-strict-rules

A set of additional rules for PHPStan based on best practices followed at TheCodingMachine
PHP
273
star
5

kickoff-docker-php

🐳 🐘 πŸš€ Easily setup a PHP project with Docker
Shell
208
star
6

symfony-vuejs

Source code of the tutorial "Building a single-page application with Symfony 4 and Vue.js"
PHP
179
star
7

tdbm

The Database Machine is a PHP ORM that requires no configuration. The object model is deduced from the database model.
PHP
115
star
8

nodejs-installer

An installer package that let's you install NodeJS and NPM as a Composer dependency.
PHP
108
star
9

safe8

All PHP functions, rewritten to throw exceptions instead of returning false, now for php8
PHP
106
star
10

gotenberg-php-client

PHP client for the Gotenberg API
PHP
104
star
11

discovery

Publish and discover assets in your PHP projects.
PHP
101
star
12

symfony-boilerplate

An example of an application built with Symfony 5, GraphQL and Nuxt.js
PHP
100
star
13

phpstan-safe-rule

A PHPStan rule to be used with the thecodingmachine/safe package
PHP
55
star
14

best-practices

This repository contains the files to generate the http://bestpractices.thecodingmachine.com website
Less
53
star
15

mouf

The Mouf PHP framework: an open-source PHP framework providing an easy way to download, install, use and reuse components, with a graphical user interface.
PHP
50
star
16

gotenberg-go-client

Go client for the Gotenberg API
Go
47
star
17

gitlab-registry-cleaner

A simple Docker image to be used in Gitlab CI to easily delete images in the Gitlab registry
Shell
44
star
18

packanalyst

Packanalyst is a service that let's you browse in any PHP class / interface / trait defined in Packagist
JavaScript
35
star
19

graphqlite-bundle

A Symfony bundle for thecodingmachine/graphqlite.
PHP
31
star
20

dbal-fluid-schema-builder

Build and modify your database schema using Doctrine DBAL and a fluid syntax.
PHP
25
star
21

symfony-middleware

This package provides a StackPHP middleware that can be used to use a Symfony application as a middleware (instead of an app)
PHP
23
star
22

html.widgets.statsgrid

This PHP package contains a HTML pivot table. You provide it with a data set and the list of columns and rows and it will display a nice pivot table.
PHP
22
star
23

magic-query

A very clever library to use SQL prepared statement with a variable number of parameters... and much more!
PHP
21
star
24

redux-toolkit-wrapper

Redux-toolkit wrapper used to write less code regarding classic CRUD operations.
TypeScript
19
star
25

rnb-plugin-typescript

This plugin allow thecodingmachine react-native-boilerplate πŸ™ users to translate the boilerplate from Javascript πŸ’› to Typescript πŸ’™
TypeScript
18
star
26

yaml-tools

A set of CLI tools to manipulate YAML files (merge, edit, etc...)
Python
18
star
27

symfony-psr15-bridge

A bridge between Symfony middlewares (StackPHP) and http-interop middlewares for converting Symfony Http abstractions to PSR-15 and back.
PHP
17
star
28

graphqlite-laravel

A Laravel service provider package to help you get started with GraphQLite in Laravel.
PHP
16
star
29

picotainer

A minimalist PHP dependency injection container compatible with ContainerInterop
PHP
15
star
30

deeployer

A tool to ease the creation of environments using docker-compose or Kubernetes
PHP
14
star
31

whoops-stackphp

This package contains a StackPHP middleware that catches all exceptions and redirects those to the Whoops error handling library.
PHP
14
star
32

graphql-controllers

Write your GraphQL queries in simple to write controllers (using webonix/graphql-php).
PHP
12
star
33

database.tdbm

The Database Machine is a PHP ORM that requires no configuration. The object model is deduced at runtime from the database model.
PHP
11
star
34

react-native-workshop

Code examples that can be implemented using TheCodingMachine React-Native Boilerplate
JavaScript
11
star
35

silex-middleware

This package provides a StackPHP middleware that can be used to plug a Silex application
PHP
11
star
36

docker-images-nodejs

A set of Node.js Docker images
Shell
10
star
37

yaco

YACO (Yet Another COmpiler) is a PHP tool that generates a PHP container based on entry definitions.
PHP
10
star
38

classname-mapper

Provides a way to find in which PHP files a class will be looked upon.
PHP
10
star
39

class-explorer

Find the list of all your PHP classes and more.
PHP
9
star
40

drupal

This Composer package is an installer that will download Drupal from the http://drupal.org website and unpack it at the root of your Composer project.
9
star
41

print.service

PDF, docx, html generator service of docx or twig template
PHP
8
star
42

map-optimizer

A tool to automatically optimize a Tiled map for usage in Phaser 3
JavaScript
8
star
43

funky

Write service providers easily using annotations
PHP
7
star
44

csrf-header-check-middleware

A PHP PSR-15 (http-interop) compliant middleware that defends your application against CSRF attacks.
PHP
7
star
45

interop.silex.di

This project is a very simple extension to the Silex microframework. It adds to Silex the capability to use any DI container (not only Pimple).
PHP
7
star
46

tdbm-bundle

A Symfony bundle for TDBM.
PHP
6
star
47

schema-analyzer

A package that offers utility tools to analyze database schemas (on top of Doctrine DBAL)
PHP
6
star
48

utils.session.optimistic-session-handler

Session handler that releases session lock quickly. Usefull for multiple ajax calls on the same page
PHP
6
star
49

graphqlite-symfony-validator-bridge

Adds support for Symfony Validator in GraphQLite
PHP
6
star
50

metahydrator

A configurable implementation of mouf's Hydrator interface
PHP
6
star
51

workadventure-map-forumphp

A WorkAdventure map for AFUP's ForumPHP 2020 event
HTML
5
star
52

crystal-project

This package contains the everaldo icon set. This is a set of icons that can be used in any web application.
5
star
53

splash-router

A PSR-15 compliant router using annotations
PHP
5
star
54

alias-container

This package contains a really minimalist dependency injection container that can be used to create aliases of instances in existing containers.
PHP
5
star
55

docker-images-mysql

MySQL container with top-notch developer experience
Shell
4
star
56

workadventure-php-community-map

A map for the PHP community on WorkAdventure
JavaScript
4
star
57

service-provider-bridge-bundle

This Symfony Bundle enables Symfony applications to use service providers as defined in container-interop/service-provider
PHP
4
star
58

utils.common.conditioninterface

This package contains one interface for condition, and a few classes that implement it. A condition is a class that possesses an "isOk" method. The condition returns true if the condition is met, and false otherwise.
PHP
3
star
59

fluid-hydrator

PHP
3
star
60

DBFaker

Easy test data in your database !
PHP
3
star
61

prefixer-container

This package contains a really minimalist dependency injection container that acts as a proxy in front of a target container. Its goal is to prefix all instances names in the target container.
PHP
3
star
62

middleware-list-universal-module

Cross-framework module providing a service containing a list of middlewares
PHP
3
star
63

gitlab-hook-middleware

A PSR-15 middleware to handle Gitlab hooks
PHP
3
star
64

laravel-universal-service-provider

This bridge allows Laravel applications to use service providers as defined in container-interop/service-provider
PHP
3
star
65

tdbm-laravel

A Laravel service provider package to help you get started with TDBM in Laravel
PHP
3
star
66

swift-twig-mail-template

This package contains a utility class to render Swift mail messages using Twig for templating
PHP
3
star
67

archive-installer

This is a simple installer that let's you create simple Composer packages that are actually downloading and extracting an archive from the web.
PHP
3
star
68

database.doctrine-orm-wrapper

This package contains wrapper classes that make Doctrine ORM easy to use in Mouf
PHP
3
star
69

mvc.bce

BCE is made to make your live easy. It will help you in building forms very quickly, handles form rendering, both client and server-side validation, and persistance.
PHP
3
star
70

mvc.splash-common

The Core part of Splash (an MVC framework). It is used by Splash itself, but also by Drusplash (the Splash wrapper for Drupal)
PHP
3
star
71

rnb-toolbox

Toolbox to create amazing plugins for our react-native boilerplate. 🧰
TypeScript
2
star
72

mvc.splash

A MVC framework deeply integrated with Mouf
PHP
2
star
73

kickoff-docker-php-images

Base images of kickoff-docker-php
Roff
2
star
74

gitlab_scrutinizer_hook_adapter

This project is an adapter between Gitlab web hooks and Scrutinizer post-receive hook triggers
PHP
2
star
75

gitlab-registry-api

Library to use the Gitlab registry api in php
PHP
2
star
76

tom-cli

A dedicated CLI for TheCodingMachine React-Native Boilerplate !
JavaScript
2
star
77

graphqlite-universal-service-provider

Cross-framework module for GraphQLite using container-interop/service-provider
PHP
2
star
78

easy-entity-reader

This Drupal 8 module helps developers access entity content.
PHP
2
star
79

tdbm-graphql

A class generator that will generate GraphQL types from your database schema (using thecodingmachine/graphqlite)
PHP
2
star
80

k8s-gitlabci

PHP
2
star
81

utils.log.psr.multi-logger

This package contains a PSR-3 compatible logger that wrap a set of loggers
PHP
2
star
82

cache-utils

Store file related cache items easily
PHP
2
star
83

tdbm-graphql-bundle

A Symfony bundle for thecodingmachine/tdbm-graphql.
PHP
2
star
84

jquery.tcm.monthpicker

The jQuery TCM Monthpicker is a highly configurable plugin that adds monthpicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.
2
star
85

html.tags

This package contains a pure PHP object representation of HTML5 tags. There is one class for each existing HTML tag, and one getter/setter per attribute.
PHP
2
star
86

lazy-array

This package provides an array than can lazily instantiate the objects it contains.
PHP
1
star
87

integration.joomla.moufla-joomlaplugin

This is the plugin that integrate Mouf in a Joomla environment. There are two other repositories that are linked to this one.
PHP
1
star
88

service-provider-utils

This package contains a set of tools to work with container-interop's service-providers.
PHP
1
star
89

quiz-demo-joomla

PHP
1
star
90

common-factories

This project provides utility factories that can be used directly in service providers complying with the container-interop/service-provider standard.
PHP
1
star
91

container-discovery

Allowing discovery of container objects through Puli
PHP
1
star
92

drupal-stratigility-bridge

This Drupal 8 module provides a bridge to include PSR-15 middlewares through Stratigility.
PHP
1
star
93

yaml-definition-loader

Provides a loader that can convert YAML files to container definitions compatible with the definition-interop standard.
PHP
1
star
94

tdbm-hydrator

A PHP hydrator allowing easy mapping between an array and an object.
PHP
1
star
95

utils.i18n.fine.language-detection

Language detection is a PHP internationalisation package, it depends of translation-interface. This package contain many class to return a language select for internationalisation.
PHP
1
star
96

html.html_element

This package contains the HtmlElementInterface interface that can be used to output HTML on a page. It also features base classes implementing this interface.
PHP
1
star
97

html.widgets.fileuploaderwidget

This package contains an upload widget based on File Uploader plugin. This allows easy uploading of files in AJAX or HTML5.
PHP
1
star
98

security.daos.tdbm

This package contains a basic user/role/right database model for TDBM.
PHP
1
star
99

symfony-cache-universal-module

Cross-framework module for Symfony cache
PHP
1
star
100

interop.symfony.di

This package contains an implementation of the Symfony 2 DI container that can be extended using other DI containers (from other frameworks).
PHP
1
star