Quantcast
Channel: PHP Annotated Monthly : The PhpStorm Blog | The JetBrains Blog

PHP Annotated – August 2020

$
0
0

PHP Annotated Monthly

Greetings everyone,

Please welcome the August installment of PHP Annotated!

PHP 8 has reached feature freeze and received a few last big additions: the nullsafe operator, named arguments, and saner string to number comparison. The syntax for attributes, though, has not yet been decided. Read the full story behind the attributes from the initial proposal to the latest revote and the battle between #[] and @[]. And as usual, we’ve got a load of useful articles, tools, videos, and podcasts for you in this issue.

(more…)


PHP Annotated – September 2020

$
0
0

PHP Annotated Monthly

Greetings everyone,

I hope you are all ready for September’s installment of PHP Annotated!

In it, we have the additional PHP 8 beta 4 release, the PHP community’s momentum with the generics discussion in Internals, and the Community Synergy Initiative. There are some interesting releases like Laravel 8, Composer 2.0 RC 1, and PoC for PHP support for GraalVM. And as usual, we’ve got a load of useful articles, tools, videos, and podcasts for you too.

(more…)

PHP Annotated – October 2020

$
0
0

PHP Annotated Monthly

Greetings everyone!

In our October edition of PHP Annotated you can read about the upcoming PHP 8, Xdebug 3 beta, short functions, and multiline arrow functions proposals in Internals. And as usual, we’ve got a load of useful articles, tools, videos, and podcasts to tell you about, too.

(more…)

PHP Annotated – January 2021

$
0
0

PHP Annotated Monthly

Greetings everyone,

In this edition of PHP Annotated, read about the top PHP news from the year so far. These include PHP 8.0.1 and other releases, fibers for async PHP, Enums, first native attributes, and other proposals for PHP 8.1. And as usual, we’ve got a load of articles, tools, videos, and streams, carefully selected for you.

(more…)

PHP Annotated – February 2021

$
0
0

PHP Annotated Monthly

Greetings everyone,

In this edition of PHP Annotated, you can read about the latest release of PHP, updates of PSR standards, and the new RFC proposals. As usual, we’ve curated a collection of PHP-related articles, tools, videos, and streams to share with you.

(more…)

PHP Annotated – March 2021

$
0
0

PHP Annotated Monthly

Greetings everyone,

In this edition of PHP Annotated, read about the latest proposals for PHP 8.1, releases of xdebug.cloud, RoadRunner 2.0, and the newly proposed PSR ClockInterface standard. And as usual, we’ve got a load of articles, tools, videos, and streams carefully selected for you.

⚡ News

🐘 PHP Internals

  • ✅ [RFC] Enumerations
    PHP 8.1 will have long-awaited enums!
    enum RfcStatus {
        case Draft;
        case UnderDiscussion;
        case Accepted;
    }
    
    function setRfcStatus(RfcStatus $status) :void {
        // ...
    }
    
    setRFCStatus(RfcStatus::Accepted); // Ок
    setRFCStatus('Draft');             // TypeError
    
    If you like the enums feature, please consider sponsoring the authors of this RFC: Ilija Tovilo and Larry Garfield.

    Read more about enums in Brent Roose’s article and some more on php.watch.

    Symfony has already opened tickets to add enums support.
  • ✅ [RFC] Deprecate passing null to non-nullable arguments of internal functions
    In the current versions of PHP, standard functions can accept null as an argument when the parameter is not nullable without any errors.

    To fix this inconsistency, in PHP 8.1 built-in functions will throw a Deprecation notice, and in PHP 9 they will throw a TypeError. For example, str_contains("", null). 3v4l.org/OVoa0A.
  • ✅ [RFC] Array unpacking with string keys
    Unpacking arrays will work consistently in PHP 8.1, including arrays with string keys:
    $array1 = ['a' => 'apple', 'p' => 'pear'];
    $array2 = ['b' => 'banana', 'o' => 'orange'];
    $array = [...$array1, ...$array2];
    // The same as:
    $array = array_merge($array1, $array2);
    
  • [RFC] PHP\iterable\any() and all() on iterables
    The proposal to add any() and all() functions for iterators did not pass the vote.
  • [RFC] var_representation() : readable alternative to var_export()
    The idea to add an alternative for var_export also did not find support, so for now we can use a userland alternative brick/varexporter.
  • 🗳 [RFC] Fibers
    Voting on Fibers has started. In short: this is a small but important improvement to generators that endeavors to make writing asynchronous PHP code easier. For example, like this:

    The Scheduler was removed from the RFC, so the Fiber API now provides the bare minimum and is similar to the resembling feature in Ruby.

    There were some reasonable arguments against the proposal from Swoole maintainers. As well as from Joe Watkins, the author of krakjoe/parallel extension.

    Yet, fibers seem to be a real step in the direction of asynchronous capabilities, which does not contradict either Swoole or parallel.

  • 🗳 [RFC] mysqli bind in execute
    Kamil Tekiela continues the initiative to improve mysqli. This RFC proposes adding a new optional parameter to mysqli_stmt::execute() that will take an array of values and bind them automatically. Currently, you have to make a separate call to mysqli_stmt::bind_param(), which only accepts variables passed by reference.
  • [RFC] New in initializers
    In the current versions of PHP, initializers such as the default values of properties, parameters, and constants can only have constant values.

    When non-constant values are needed, properties can be initialized in a constructor, and arguments can be initialized in the method’s body. With constants, there are no such options at all.

    Nikita Popov proposes to make it possible to use objects as default values for properties, parameters, and any constants and static variables.

    static $x = new Foo();
    
    const C = new Foo();
    
    class Bar
    {
        public const CONSTANT = new Foo();
        public static Foo $staticProperty = new Foo();
    
        #[Assert\All([new Assert\Uuid()])]
        public array $uuids = [];
    
        public function __construct(
            private Logger $logger = new NullLogger()
        ) {}
    }
    
    function test($param = new Foo()) {}
    

    For now, the proposal is limited to the new operator, but the implementation allows extending support for other expressions in the future.

    An additional bonus (or an intention? 🤔) is that objects will be allowed in the attributes. That solves the problem with nested attributes.
  • [RFC] CachedIterable (rewindable, allows any key&repeating keys)
    Tyson Andre suggests adding a caching iterator. It stores the state of an iterator and internally contains immutable copies of its keys and values.
  • [RFC] Namespaces in bundled PHP extensions
    All classes and functions provided by bundled PHP extensions are currently located in the global namespace (with one exception).

    This RFC proposes a convention on using namespaces with bundled extensions. Basically, the extension name should be used as a namespace and no PHP prefix is needed. For example, OpenSSLCertificate can become OpenSSL\Certificate.

    So far, however, this only applies to new symbols added, and the migration of existing functions and classes is not affected by this RFC. But the examples show possible future transformations:
    str_contains() -> String\contains()
    in_array() -> Array\contains().
  • [RFC] noreturn type
    The authors of Psalm and PHPStan suggest adding a new type to PHP – noreturn.

    The authors of Psalm and PHPStan suggest adding a new type to PHP – noreturn. This would be a bottom type indicating that a function either always throws an exception or terminates execution, i.e. calls exit(), die(), trigger_error().
    function redirect(string $uri): noreturn {
        header('Location: ' . $uri);
        exit();
    }
    
    function redirectToLoginPage(): noreturn {
        redirect('/login');
    }
    

    There is a similar type in Hack and in Python, and it has been used in Psalm, PHPStan, and also in PhpStorm as an attribute #[NoReturn] or via an exitPoint() in .phpstormmeta.php.

phpstorm PhpStorm

🛠 Tools

Symfony

Laravel

Yii

💡 Misc

📺 Videos

🔈 Podcasts

  • php[architect] podcast #50 – Discussed the Mezzio framework, functional programming, and software dependency security.
  • PHP Ugly podcast:
    #227: – Math is Hard.
    #226: – Help Wanted, PHP Release Manager.
  • PHP Internals News podcast:
    #75 – With Nikita Popov on deprecating null, array unpacking, restrict globals usage, and phase out serializable.
    #76 – Another one with Nikita Popov about restricting the use of globals, and phasing out serializable.
    #77 – With David Gebler about the fsync() function added to PHP 8.1.
    #78 – With Andreas Heigl on moving PHP documentation to Git.

Thanks for reading!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop

PHP Annotated — May 2021

$
0
0

PHP Annotated Monthly
Greetings everyone!

PHP 8.0 is gaining momentum and adoption is increasing, as evidenced by Composer’s statistics.

Meanwhile, PHP internals have accepted a bunch of changes for PHP 8.1, including a new never type and namespaces in bundled PHP extensions, and some features that will be deprecated.

The PHP 8.1 release managers have been selected, and there are several interesting proposals under discussion, including property accessors, pure intersection types, and final constants.

Read more about this news in the May edition of PHP Annotated. As usual, we’ve carefully selected a collection of articles, tools, videos, and streams for you.

⚡ News

  • PHP Versions Stats – 2021.1

    The traditional compilation of statistics based on the data that Composer sends when it connects to packagist.org:

    • PHP 7.4: 45.92% (+3.31)
    • PHP 7.3: 21.30% (-5.75)
    • PHP 7.2: 12.89% (-2.39)
    • PHP 8.0: 9.44% (+9.17)
    • PHP 7.1: 5.21% (-2.24)
  • PHP is available on Google Cloud Functions

    Google Cloud’s serverless platform now natively supports PHP. With GoogleCloudPlatform/functions-framework-php/ you can run functions in a PHP 7.4-based runtime.

    There are a few more details in the discussion on GitHub in the Symfony repository. Symfony 5.3 should run on GCF smoothly, thanks to the Runtime component. You just need to install php-runtime/google-cloud.

  • Composer Command Injection Vulnerability

    The vulnerability in Composer only affects systems that have Mercurial installed. However, it is worth immediately updating to versions 2.0.13 and 1.10.22, which contain fixes. Check out a more detailed technical analysis of the vulnerability.

  • Follow up on git.php.net attack

    Attackers pushed two commits to the PHP source on behalf of Rasmus Lerdorf and Nikita Popov. The problem was quickly detected and solved. The malicious code did not get to users.

    As it turned out, the git.php.net server allowed commits via HTTPS and used digest authentication, which accepts md5 hash as a secret. The hash database of all the contributors was obtained by the attackers from master.php.net, which was probably the server that was originally compromised.

    As a result, all development has been fully moved to GitHub, which makes life easier for language developers.

  • PHP 7.4.19, PHP 8.0.6 – With a fix in PDO_pgsql.

🐘 PHP Internals

  • ✅ [RFC] never type

    PHP 8.1 will have a new type for returned values: never.

    A function or method declared with the never type indicates that it will never return a value, and it either throws an exception or terminates with a call of type die(), exit(), trigger_error().

    It is an empty bottom type and is a subtype of all other types, and there are similar types in Python, Rust, Kotlin, and TypeScript. This type improves static analysis.

    function redirect(string $uri): noreturn {
        header('Location: ' . $uri);
        exit();
    }
    
    function redirectToLoginPage(): noreturn {
        redirect('/login');
    }

    You can find more details on PHP.Watch or listen to the PHP Internals News podcast with Matt Brown and Ondřej Mirtes.
  • ✅ [RFC] Deprecate implicit non-integer-compatible float to int conversions

    In PHP 8.1, an E_DEPRECATED notice will be thrown when float is converted into int and fractional part is lost. Later, in PHP 9.0, this will cause a TypeError.

    function acceptInt(int $i) {
            var_dump($i);
    }
    acceptInt(3.1415);
    
    > int(3) // Deprecation notice

    Learn more from the 🔈 PHP Internals News podcast #83 with George Peter Banyard.
  • ✅ [RFC] Phasing out Serializable

    In PHP 8.1 the Serializable interface will be deprecated. A deprecation notice will be thrown when the class uses only this interface, that is, if the class does not additionally have the new magic methods __serialize() and __unserialize().

  • ✅ [RFC] Namespaces in bundled PHP extensions

    This marks a small step towards cleaner PHP! New symbols (classes, interfaces, etc.) in extensions will now have to use namespaces.

    Here’s an example. The resource type is de-facto obsolete in PHP, and all existing resources are slowly being migrated to objects. In PHP 8.1 some resources will be replaced with the following namespaced classes:

    IMAPConnection -> IMAP\Connection
    FTPConnection -> FTP\Connection
    LDAP -> LDAP\Connection
    LDAPResult -> LDAP\Result
    LDAPResultEntry -> LDAP\ResultEntry
    PgSql -> PgSql\Connection
    PgSqlResult -> PgSql\Result
    PgSqlLob -> PgSql\Lob
  • ✅ [RFC] Add return type declarations for internal methods

    Most of the built-in methods in PHP 8.0 have received parameters and return type declarations. In some cases, however, this could not be done, like for the return values of public non-final methods. The problem is that they can be overridden in user code.

    Here is an example to illustrate the problem

    class SomeStandardClass
    {
        public function method(): int {}
    }
    
    class UserClass extends SomeStandardClass
    {
        public function method() {}
    }
    
    // Fatal error: Declaration of UserClass::method() must be compatible with SomeStandardClass::method()
    

    There will now be a gradual migration for such cases. In PHP 8.1, all internal methods will also get the missing types. If they are overridden in user code, a Deprecation notice will be thrown.

    class MyDateTime extends DateTime
    {
        public function modify(string $modifier) { return false; }
    }
    
    // Deprecated: Declaration of MyDateTime::modify(string $modifier) should be compatible with DateTime::modify(string $modifier): DateTime|false
    
  • Release managers for PHP 8.1 have been selected

    There will be three managers this time around: the experienced Joe Watkins (pthreads, parallel, pcov), and two newcomers, Patrick Allaert (blackfire.io) and Ben Ramsey (ramsey/uuid). Check PHP Internals News podcast #84 with Ben and Patrick.


    New proposals for PHP 8.1:

  • [RFC] Partial Function Application

    Partial function application (partial functions) is when only some arguments are bound on function call, and the others remain as parameters to be passed later.

    For example, here is a full function:

    function whole($one, $two) {
        /* ... */
    }

    And here’s a partial one based on it:
    $partial = whole(?, 2);

    In this case, the partial signature will look like this:
    function($one) {
        /* ... */
    }

    Why is this needed?

    Firstly, you can now get a reference to any function or method and pass it wherever Callable is expected. For example, you could do this

    array_map(Something::toString(?), [1, 2, 3]);
    array_map(strval(?), [1, 2, 3]);
    
    // instead of
    array_map([Something::class, 'toString'], [1, 2, 3])
    array_map('strval', [1, 2, 3]);

    And secondly, as a consequence, it will be possible to implement the pipe operator |>:
    $result = "Hello World"
        |> htmlentities(?)
        |> explode(?);

    See it in action at 3v4l.org.

    Thanks to Larry Garfield, Joe Watkins, Levi Morrison, and Paul Crovella for the RFC and the implementation.

  • [RFC] Property Accessors

    Nikita has finalized the implementation of the property accessors, and the proposal is now officially under discussion.

    The bottom line is that traditional getters and setters are not convenient to use, and the magic methods __get and __set are not specific. The new accessors are meant to fix these issues.

    The syntax is inspired by C#:

    class Foo {
        public $prop {
            get { /* ... */ }
            set { /* ... */ }
        }
    }
    

    You can use them to implement read-only properties:
    class User {
        public string $name { get; }
    
        public function __construct(string $name) {
            $this->name = $name;
        }
    }
    

    And you can specify asymmetric access, i.e. make them public or private separately for reading and writing:
    class User {
        public string $name { get; private set; }
    
        ...
    }
    

    Or you can use them as full-fledged methods for validation or other actions:
    class Foo {
        public int $bar {
            get {
                error_log('Getting $bar');
                return $this->bar;
            }
            set {
                assert($bar > 42);
                $this->bar = $bar;
            }
        }
    }
    
  • [RFC] Pure intersection types

    Union types were added in PHP 8.0, and this RFC proposes to add intersection types.

    The syntax is TypeA&TypeB, and it means that the variable must be both instanceof TypeA and instanceof TypeB.

    Details

    class A {
        private Traversable&Countable $countableIterator;
    
        public function setIterator(Traversable&Countable $countableIterator): void {
            $this->countableIterator = $countableIterator;
        }
    
        public function getIterator(): Traversable&Countable {
            return $this->countableIterator;
        }
    }
    

    The proposal is called “pure intersection types” because combinations with union types are not supported and are being left for future consideration. Aliases for complex types are also being left for the future.

  • [RFC] Deprecate ticks

    There is a tick mechanism in PHP: declare(ticks=1). It was originally needed to track pcntl signals. Now you can use pcntl_signal() and pcntl_async_signals() for this, which is why there’s been a suggestion to deprecate ticks in PHP 8.1 and remove them completely in PHP 9.

  • [RFC] Final class constants

    The author of this RFC proposes a final modifier for constants, so that they cannot be overridden in child classes.

    Details

    class Foo
    {
        final public const X = "foo";
    }
    
    class Bar extends Foo
    {
        public const X = "bar";
    }
    
    // Fatal error: Bar::X cannot override final constant Foo::X
    

    Fun fact from RFC: constants in interfaces are already final.

  • A couple more links for those who would like to start contributing to PHP source:

🛠 Tools

Symfony

Laravel

Yii

PhpStorm

💡 Misc

📺 Videos

🔈 Podcasts

🙌 Community

  • PHP’s bus factor is 2 – Joe Watkins says that only two people know enough about the PHP source, so we should consider this when thinking about adding new features to PHP. He also says that we need more developers working on the core.

Thanks for reading!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop

PHP Annotated — August 2021

$
0
0

PHP Annotated Monthly

Greetings everyone!
PHP 8.1 has reached the second beta and the list of changes has been finalized. The final piece left to decide on is the nullability of intersection types, which is being voted on right now.

Meanwhile, PHP internals are already discussing features for the next release. Read on to learn about the first two RFCs for PHP 8.2, which is coming in 2022.

As PHP 8.1 is going to have fibers, two popular async frameworks for PHP have agreed to join forces and work together on shared abstraction.

You can read more about this news in the August edition of PHP Annotated. As usual, we’ve carefully selected a collection of articles, tools, videos, and streams for you.

⚡ News

  • PHP 8.1.0, Beta 2

    The beta releases signal the end of the active development phase of PHP 8.1, which means that the list of new features and changes can be considered final (with the exception of nullable intersection types). The third and final beta is expected August 19.


    Image by Peter Kokot.

    So what’s coming in PHP 8.1?
    Here is a shortlist of the most notable changes:

    • Enums (RFC).
    • First-class callables (RFC).
    • Readonly properties (RFC).
    • New operator in initializers (RFC).
    • Brand new never type for return values (RFC).
    • Fibers (RFC).
    • Final constants in classes (RFC).
    • Spread operator supporting string array keys (RFC).
    • Deprecation of implicit non-integer-compatible float to int conversions (RFC).
    • Deprecation of serializable interfaces (RFC).
    • Explicit octal notation with the 0o prefix (RFC).
    • Restricted usage of $GLOBALS (RFC).

    If you’d like to learn more, check out this awesome compilation of PHP 8.1 “before” and “after” examples.

    There is also a 10-day newsletter from Brent Roose: The Road to PHP 8.1.

    And a full description of all the changes is available on PHP.Watch: php.watch/versions/8.1.

    PHP.Watch also has a post on Directory Uploads in PHP 8.1 – In PHP 8.1 the $_FILES array will contain a full_path section with directory structure paths from the user. This is needed to support directory uploading.

  • ReactPHP and AmpPHP join forces

    With the addition of fibers in PHP 8.1, asynchronous PHP code may be a little easier and prettier. The maintainers of two popular libraries for asynchronous PHP have announced the RevoltPHP project. They plan to make a common event loop and implement shared abstraction over fibers.

  • PhpStorm 2021.2 has been released

    Check out this blog post that contains all the details about generics support, enums, array shapes, and everything else that is being introduced in this release.

  • PHP 7.4.22, PHP 8.0.9

    Security and bugfix updates for current branches.

🐘 PHP Internals

  • [RFC] Nullable Intersection types

    Shortly after the adoption of the RFC on type intersections, a comment was posted by Nikolas Grekas (Symfony core). He said that without the ability to make them nullable, the intersections are much less interesting.

    Technically, the PHP 8.1 branch is already frozen, but the PHP team decided to make an exception for this proposal.

    class Foo
    {
        public (X&Y)|null $bar;
    
        function setBar((X&Y)|null $bar = null): (X&Y)|null
        {
            return $this->bar = $bar;
        }
    }
    

    Syntax choice is also put to a vote: ?X&Y or (X&Y)|null.
  • [RFC] Unwrap reference after foreach

    In the current versions of PHP, there is no dedicated scoping for the foreach loop. This has a very counterintuitive consequence: the reference to the $value and the last element of the array remain even after the foreach loop ends.

    The problem is easily illustrated by this example:

    $array = [0, 1, 2];
    foreach ($array as &$value) { /* ... */ }
    // without calling unset($value),
    // $value still points to the last element: $array[2]
    
    foreach ($array as $value) {
    // $array[2] will be updated each time with the values of $array
    }
    var_dump($array);
    
    // Before RFC:
    >
    array(3) {
        [0] => int(0)
        [1] => int(1)
        [2] => &int(1)
    }
    
    // After RFC:
    > array(3) {
        [0] => int(0)
        [1] => int(1)
        [2] => int(2)
    }
    

    This RFC proposes a fix for this logically correct, but buggy-looking, behavior. After the foreach loop, the reference to $value will be removed.
  • [RFC] Never For Parameter Types

    In PHP 8.1 there will be a new type, never, for return values. For PHP 8.2, there is already a proposal to use never as the type for parameters.

    The author of the RFC, Jordan LeDoux, thinks that never will be useful in abstract classes and interfaces. You could use it to specify that the parameter must be typed in some way.

    This could help to mimic the behavior of generics. However, you will still have to resort to the type descriptions in PHPDoc for static analyzers and PhpStorm.

    interface CollectionInterface {
        public function add(never $input): self;
    }
    
    class A implements CollectionInterface {
        public function add(int $input): self {}
    }
    

🛠 Tools

  • frontdevops/php-evil – An extension to disable eval(). It turns out that eval() is not a function, but a language construct, so disable_functions will not help to forbid it. So the author had to write his own micro-extension.
  • beyondcode/expose 2.0 – A cool tool for sneaking local services into the world. This should be useful for testing webhooks or demoing apps.
  • EcotoneFramework – An interesting service bus for DDD, CQRS, and Event Sourcing in PHP. It works in PHP 8+ via attributes, with good documentation and integrations for Laravel and Symfony. Here is an example of a CQRS implementation.
  • PHP-CSS-Parser – A Parser for CSS files written in PHP. This allows the extraction of CSS files into a data structure, manipulation of said structure, and output as (optimized) CSS.
  • Psalm 4.9.0 – The first community release of Psalm after Matt Brown, the author, left the project.
  • ergebnis/composer-normalize – A plugin for Composer that makes the composer.json file look nice.
  • paragonie/paseto 2.0 – Stateless-token, a safe alternative to JWT.
  • chrome-php/chrome v1.0.0 – A package to control Chrome/Chromium in headless mode.
  • darsyn/ip – Immutable value objects for working with IP addresses, including helpers for Doctrine
  • MadLisp – A Lisp interpreter written in PHP.

Symfony

Laravel

Yii

PhpStorm

  • i18n Ally – A nice plugin for PhpStorm for making easy work of translation strings. It’s automatically configured for Laravel and Symfony, and it can be manually configured for Yii, CodeIgniter, and CakePHP.
  • Laravel Idea 4.4 – A big update to the plugin.
  • 📺 Source diving the PhpStorm Pest plugin – Cool stream recording where Oliver Nybroe shows how to develop PhpStorm plugins.

💡 Misc

📺 Videos


Thanks for reading, we hope you have a great day!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop


PHP Annotated — September 2021

$
0
0

PHP Annotated Monthly

Greetings everyone!
PHP 8.1 has reached the first release candidate and the list of changes has been finalized. We’ll see at least 5 more release candidates before the final release, which is planned for the end of November.

Meanwhile, discussions are already taking place in PHP internals regarding three more proposals for PHP 8.2: operator overloading, the $this type hint, and deprecating dynamic properties.

Beware of malware Composer packages! Two of them were recently discovered on Packagist.

PHP-FIG discusses adding a new type of standard to PSRs.

You can read more about this news in the September edition of PHP Annotated. As usual, we’ve carefully selected a variety of excellent articles, tools, videos, and streams for you.

⚡ News

  • PHP 8.1.0 RC 1

    The final release is still two and a half months away with at least 5 release candidates coming.

    The final release of version 8.1 is still two and a half months off, with at least 5 release candidates on the way. Here’s a micro tutorial on how to install PHP 8.1 on macOS via Homebrew. Additionally, PHP 8.1 has ready-made Docker images.

    You can find a comprehensive description of what’s coming in PHP 8.1 at php.watch/versions/8.1 and on Brent Rooses’s blog, stitcher.io/blog/new-in-php-81.

  • PHP 8.0.10, PHP 7.4.23, PHP 7.3.30

    Security and bugfix updates for current branches.

  • The end of Swiftmailer

    The popular mail package Swiftmailer will only be supported until November. It will be replaced by symfony/mailer.

    Symfony/mailer’s features and concepts replicate Swiftmailer, so migrating should be fairly easy. Rector has a migration script, and it simply needs to rename classes.

  • PHP Evolving Recommendations (PERs)

    PHP-FIG currently releases only PSP standards. The problem is that some standards require constant refinement. For example, in the case of code styles, PSR-12 replaced PSR-2, and now it does not include new features from PHP 7.4-8.0.

    There is now a proposal to adopt a special type of recommendation called PER, which can be changed over time.

  • Malware Composer packages

    On Packagist, there was a package called symfont/process which did exactly the same thing as symfony/process, but it also gathered information about the machine, sent it to a third party, and opened a web shell.

    The attacker expected that users would potentially misspell the package name during installation and type symfont instead of symfony.

    The malware package has already been removed from both Packagist and GitHub, and an analysis of how it worked is available.

    Another backdoor was found in the laraveli/qr-code package. As you can see from the code, the malware was copying this type of web shell onto the machine.

    To protect yourself from attacks like these, you can add a local-php-security-checker to your CI pipeline or use the the-php-security-checker GitHub Action.

    For more complex cases, you can run the marcocesarato/PHP-Antimalware-Scanner.

  • The hautelook/alice-bundle repository was removed from GitHub

    The package has more than 8 million downloads, and the main contributor doesn’t know why he was removed from the maintainers list and the repository was apparently made private.

    A working fork is available on Théo’s GitHub profile: theofidry/AliceBundle.

🐘 PHP Internals

  • [RFC] Deprecate dynamic properties

    In current versions of PHP, if you try to write to a property that doesn’t exist, it will be automatically created.

    In modern code, writing to a nonexistent property is rarely done intentionally – it is usually a mistake.

    This RFC proposes to deprecate and subsequently remove the ability to create dynamic (undeclared) properties.

    class User {
        public $name;
    }
    
    $user = new User;
    
    // Assigns declared property User::$name.
    $user->name = "foo";
    
    // Oops, a typo:
    $user->nane = "foo";
    
    // PHP 8.2: Throws a warning but still creates a dynamic property.
    // PHP 9.0: Throws Error exception.
    

    This change would not apply to stdClass and its inheritors. The behavior of magical methods __get/__set would also be unaffected by this change.
    $obj = (object) []; // = new stdClass;
    
    // No deprecation warning
    $obj->foo = 1;
    
    class myStdClass extends stdClass {}
    $obj2 = new myStdClass;
    
    // No deprecation warning
    $obj2->bar = 1;
    

    With this change in PHP 9.0, it would be possible to reduce the size of objects by 8 bytes. For a single object, of course, this is nothing. But cumulatively for large applications it could result in a noticeable difference.

    There is also a discussion on whether it makes sense to alias stdClass to DynamicObject.

  • [RFC] User Defined Operator Overloads

    In this RFC, Jordan LeDoux essentially proposes to define a different magic method for each operator, e.g. __add() for `+` or __equals() for `==`.
    Using these methods would make it possible to describe the desired behavior of operators applied to objects.

    $a = new Number(8);
    $b = new Number(6);
    $c = new Number(4);
    
    // Instead of this
    $posRoot = $b->mul(-1)->add($b->pow(2)->sub($a->mul($c)->mul(4))->sqrt())->div($a->mul(2));
    
    // It would be possible do it like this
    $posRoot = ((-1 * $b) + ($b ** 2 - 4 * $a * $c)->sqrt()) / (2 * $a);
    

    If the proposal is accepted, it would become possible to implement the behavior of scalar objects in userland code.
  • [RFC] $this return type

    Nikita brought up the idea of using $this as the return value type. This would cause the interpreter to check that an object is the same as the one that is returned.

    Here is how it compares with self and static by Ben Ramsey:

    • self – The return value must be an instance of the same class that sets this type declaration.
    • static – The return value must be an instance of the same class that calls the method with this type declaration.
    • $this – The return value must be the same instance as the instance that calls the method with this type declaration.

    class Test {
        public function method(): $this {
            return $this;
        }
    
        public function not_this(): $this {
            return new self(); // Fatal Error
        }
    }
    
  • [RFC] Deprecate partially supported callables

    The following callables are currently accepted by the callable, the is_callable() function, and call_user_func(), but are not supported byn $callable().

    "self::method"
    "parent::method"
    "static::method"
    ["self", "method"]
    ["parent", "method"]
    ["static", "method"]
    ["Foo", "Bar::method"]
    [new Foo, "Bar::method"]
    

    This RFC proposes to deprecate in PHP 8.2 and remove in PHP 9.0 support for these callables.

    Normal callables like "function", "Foo::method", ["Foo", "method"], or [new Foo, "method"] would not be affected by this proposal because for them, calling with braces will work as expected:

    class Foo {
        function method() {
            echo 'method';
        }
    }
    [new Foo, "method"]();
    // > method
    
  • All PHP RFCs on GitHub

    As an experiment, Ben Ramsey, the PHP 8.1 release manager, exported all 838 RFCs ever discussed to Git, along with the change history for each.

🛠 Tools

  • whsv26/functional – The author ran into problems with existing PHP implementations of collections and wrote his own package.
  • phabelio/phabel – This transpiler for PHP makes it possible to use features from the latest PHP versions in older environments, or when backward compatibility must be maintained. You can also start adding support for features that don’t yet exist, such as the async/await keywords.
     
    Similar tools already exist, like marcioAlmada/yay or preprocess.io. And Rector can also do backports. But the special thing about Phabel is the transparent integration with Composer.
  • phparkitect/arkitect – A tool for defining and checking architectural rules for your project.
  • niklongstone/regex-reverse – Generates a random string that satisfies a given regular expression.
  • azjezz/psl – What a standard PHP library might look like.
  • github-php/sponsors – A package for working with the GitHub Sponsors API. You can organize access control by checking whether the user is a sponsor.
  • koriym/Koriym.Attributes – A simple tool that allows you to read PHPDoc annotations and PHP 8 attributes through a single interface. The more advanced spiral/attributes is also available for the same tasks.
  • grep.app – A handy tool for quick code searches on GitHub.
  • mrsuh/php-generics — PHP generics written in PHP. This is an interesting and functional attempt to implement syntax-level generics in PHP.

Symfony

Laravel

Yii

💡 Misc

🔈 Podcasts


Thanks for reading. We hope you have a great day!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop

PHP Annotated — October 2021

$
0
0

PHP Annotated Monthly

Greetings everyone!
Here are some highlights from the world of PHP over the last month.

  • PHP 8.1 RC3 is out, and the first package that uses enumerations is already available!
  • A community fork of Magento has been announced.
  • In addition to PSRs, there will be a new type of recommendation called PERs.
  • Symfony 6 will be fully typed — how to update?
  • New optimized data structures and a standalone null type have been proposed for PHP 8.2.
  • A PHP vulnerability with disable_functions has been published, though it is not actually a real vulnerability.

You can read more about this news in the October edition of PHP Annotated. As usual, we’ve carefully selected a variety of excellent articles, tools, videos, and streams for you.

⚡ News

  • PHP 8.1 RC 3

    The third release candidate was delivered on schedule. For an overview of the new features in PHP 8.1, take a look at the What’s new in PHP 8.1 and PHP 8.1: before and after posts. A comprehensive list of changes is available on PHP.Watch.

    The migration guide for PHP 8.1 is now also available.

    You can try PHP 8.1 from docker, for example with the php:8.1-rc-cli image, on Mac via homebrew, or you can just poke around at 3v4l.org.

    The first package that uses enumerations from PHP 8.1 is already available!
    alexanderpas/php-http-enum – Enums with the status codes and text of HTTP-response messages.

  • PHP 8.0.11, 7.4.24 and 7.3.31

    Updates to supported branches with the security fix CVE-2021-21706.

    This fix addresses a bug that was causing ZipArchive::extractTo to extract the zip archive outside the target directory with certain file path names on Windows.

  • The Future of Magento

    This letter from members of the Magento community announced that there would be a Magento fork run by a community organization. The goal is to ensure the long-term open-source life of Magento.

    Previously, Adobe had announced that they are planning to decompose Magento into microservices. How exactly this will happen is unclear. That’s why a fork will be created. It will be compatible with Adobe’s Magento, as long as the latter is open.

  • PhpStorm 2021.3 Early Access Program Is Open

    The PhpStorm 2021.3 Early Access Program is in full swing. Every week we publish new builds that allow you to try the new features before the official release.

    The upcoming major release will include full support for PHP 8.1, many improvements for generics, new options for deployment, an updated debugger interface, and much more.

  • PER Workflow – PHP-FIG

    PHP-FIG has approved the idea of PHP Evolving Recommendations. In addition to PSR standards, there will now be PERs, which are recommendations that can be perpetually changed and supplemented. For example, in the case of code styles, it will be possible to add new rules to reflect new language features.

  • “Vulnerability” (not) in PHP to bypass disable_functions

    A researcher recently published a method to bypass the constraints set by the disable_functions directive in php.ini.

    You can use disable_functions to forbid the use of certain functions in PHP scripts. For instance, you can forbid system, exec, proc_open and shell_exec to block calls to external programs.
    You cannot forbid eval(), by the way, because it’s not a function, but rather a language construct.

    The bypass problem cannot be called a vulnerability, because disable_functions is not a security feature and relying on it for security is a bad idea.


    Learn more about what counts as a security problem in PHP and what doesn’t: wiki.php.net/security.

    And if you’re interested in understanding the problem in more detail, there is a cool breakdown of how disable_functions works and how such exploits are built. And another one even explains how you can automatically search for such problems.

    Also, check out this analysis of a real RCE vulnerability found in fiveai/Cachet, a popular Laravel project: Code Execution via Laravel Configuration Injection.

  • composer/composer 2.1.9

    This update fixes a vulnerability on Windows (CVE-2021-41116). Windows users should definitely update.

  • PHPOpenDocs.com

    Here’s an experiment in making a community site for PHP related content.

    It already has a useful sponsoring page with a list of contributors grouped by PHP version, as well as an Internals section with lots of links to resources about the structure of PHP code and how to start contributing to PHP core.

🐘 PHP Internals

  • New data structures in PHP

    PHP has a universal array data structure that can be used as a list, an associative array, a queue, a stack, etc.

    Versatility is achieved by using a hash table under the hood. But this versatility comes at the cost of additional memory usage and subtle performance overhead.

    SPL has more-specialized data structures, but they have baggage of their own.

    Tyson Andre suggests adding new optimized data structures to PHP.

    One option to achieve that would be to add structures from the popular php-ds/ext-ds extension, but its author does not support this idea. This thread on GitHub sheds some light on the details of the debate.

    So for now there are two RFCs:

    • [RFC] final class Vector Vector structure – is a set of elements with consecutive indexes 0, 1, 2, etc. It requires half as much memory as current arrays and works faster than similar SPL structures.In terms of its API, it’s just a usual class with implementations of the
      ArrayAccess, IteratorAggregate, and Countable interfaces.
      $values = new Vector();
      for ($i = 0; $i
    • [RFC] final class Deque Deque is a doubly-linked queue, that is, elements can be added and removed both at the beginning and at the end.You could use it in the place of SplQueueue or SplDoublyLinkedList and see immediate improvements to performance and memory consumption.

      Deque is also relevant for long-running applications that use large arrays, because of their known issues with memory management.

    The implementations of these and other structures are available in the TysonAndre/pecl-teds extension.

  • [RFC] Allow null as standalone type

    George Peter Banyard proposes to add the ability to use null in type declarations.

    First, this is the missing piece for the completeness of the type system of PHP. There is a mixed type, never type was added, there are also unions and intersections, but a unit type is missing.

    Second, this type will cover some edge cases for type hinting and improve static analysis.

    For example, at the moment, you can use the pseudotype false in unions, but you cannot specify that the function returns false|null, only bool|null.

  • How opcache works

    Nikita Popov doesn’t always write blog posts, but when he does he describes the concepts clearly and in details.

🛠 Tools

  • Xdebug 3.1.0 – The popular PHP debugger has received an update. It comes with support for PHP 8.1, many fixes, and some rather minor features. Don’t miss this series of videos about Xdebug 3 by extension author Derick Rethans.
  • spiral/roadrunner 2.4 – This is a big update for the PHP application server in Golang. The release includes support for queues, key-value stores, and integration with Temporal. See details.
  • brick/date-time – A set of immutable classes for working with date and time.
  • php-runtime/runtime – The Runtime component separates the application bootstrap logic from the global state, and so allows you to run the application without changes in any environment, such as PHP-FPM, ReactPHP, Swoole, etc.
    This was originally a component for Symfony, but it turned out to be so good that it’s now a separate organization on GitHub.
  • rindow/rindow-neuralnetworks – A neural network training framework based on Python Keras. According to its documentation, GPU support is only available in experimental mode and only on Windows.
  • piko-framework/router – Yet another PHP router, this one is based on radix tree and, according to the benchmarks, is faster than the Symfony router.
  • nunomaduro/termwind – A PHP 8+ package for formatting the output of console programs with Tailwind CSS style syntax.
  • icanhazstring/random-issue-picker – If you want to participate in Hacktoberfest but don’t know where to start, here’s a tool that will pick a random issue on GitHub or GitLab for you.

Symfony

Laravel

💡 Misc

Thanks for reading!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop


PHP Annotated — January 2022

$
0
0

PHP Annotated Monthly

Greetings everyone,
Catch up on the latest from the PHP world with our specially curated news, articles, tools, and videos.

News

  • The PHP Foundation Update, January 2022
    The PHP Foundation started its work at the end of November as a non-profit organization whose mission is to ensure the long life and prosperity of the PHP language.

    We already have the first results. Applications for sponsorship from core developers have been received and are being processed.

    The foundation team will be publishing monthly updates so you can subscribe to our Twitter @thephpf to stay up to date with the news.

    To learn more about The PHP Foundation check out the Voices of the ElePHPant Ep 366 podcast with Joe Watkins, Sara Golemon, and Sebastian Bergmann.

  • PHP 8.0.15, PHP 8.1.2, PHP 7.4.27
    Bug fixes for current PHP branches have been released. In the case of PHP 7.4 this is the last regular release, and from now on only security updates will be issued for the PHP 7.4 branch.
  • PHP version stats: January, 2022
    Here are some fresh stats for PHP versions according to packagist.org. Version 8.1 only came out two months ago, but it’s already gained a 9.1% share. However, there’s still a lot of PHP 7.4 (44%).
  • [RFC] User Defined Operator Overloads
    A proposal to add operator overloading to PHP failed to pass the vote. You can, however, listen to the PHP Internals News podcast with the author Jordan LeDoux to learn the details.
    Jordan also published very thorough instructions on How to make an RFC for PHP.

    In the meantime, operator overloading can already be used in PHP thanks to lisachenko/z-engine and FFI. For an example of the implementation of operators for matrices, see: lisachenko/native-php-matrix.

Releases

  • thephpleague/flysystem 3.0.0 – A major update of the popular library for working with file systems. Check out the blog post with all the details.
  • Cycle 2.0 – The second major release of Cycle – a DataMapper and ORM for PHP that can be used in both traditional and daemonized PHP applications.
  • ankitpokhrel/tus-php 1.0 – Server and client implementation of the tus.io, an open protocol for renewable file uploads. The protocol is used, for example, in Vimeo and Cloudflare.
  • Infection PHP 0.26.0 – An update to the PHP mutation testing framework. The new version adds HTML reports, mutation of only changed strings, and more.
  • Doctrine ORM 2.11 – The update brings support for enumerations, virtual columns, read-only properties, nested attributes, and more.
  • Roave/BetterReflection 5.0 – Improved Reflection API: you can get information without loading classes, from closures, and much more. The new version adds support for PHP 8.1 and has better performance.

Tools

  • viewi/viewi – A powerful tool for creating reactive applications using only PHP and HTML. In essence, it’s a server-side template engine + frontend framework. But the zest is that you describe all components and logic in PHP and then the tool transpiles them into native JS.

    The project website viewi.net details the mechanism of operation and has code examples. You can also follow a step-by-step tutorial and check out the Symfony integration.

  • Roach PHP – A tool for web scraping inspired by the popular Python library, Scrapy.
  • symfony/html-sanitizer – A new component to clean up untrusted HTML and protect against XSS. It could be a good alternative to HTML Purifier.
  • EventSaucePHP/ObjectHydrator – A library for hydrating raw data (like JSON) into objects.
  • ajthinking/archetype – A simple interface for modifying PHP files/classes.
  • framjet/php-enum-bitmask – Using enumerations from PHP 8.1 as bitmasks.
  • beyondcode/httpdump – Laravel application for debugging incoming HTTP requests (debugging web hooks, etc.). Creates random URLs and dumps all the requests to them in a nice way. You can see it in action at httpdump.app.
  • spatie/ignition – This library for displaying debugging error pages, familiar to many from Laravel, but now framework-independent, has been updated and can be used in any application. See the overview blog post.
  • chevere/xr – A debug server on ReactPHP, inspired by the spatie/ray, but instead of a desktop application it’s just a CLI command to run. Video demo.
  • JustSteveKing/php-sdk, Sammyjo20/Saloon – Two similar libraries with the same idea: simplify SDK creation for services or organize access to different APIs in the common style.
  • AliSaleem27/wordle-cl – A CLI version of the popular five-letter word guessing game Wordle.
  • staabm/phpstan-dba – An extension for PHPStan that checks the validity of SQL queries in PDO, MySQLi, and Doctrine/DBAL. Demo.
  • flow-php/etl – An implementation of the Extract Transform Load pattern to use in your PHP application. Check out the thread from the author to learn more.

Symfony

Laravel

Yii

Misc

Community


Thanks for reading!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop


PHP Annotated — 2022 Spring Catch-up

$
0
0

PHP Annotated Monthly

Greetings everyone,

It’s been a while since the PHP Annotated Monthly was online, so hopefully we are back on track. With Brent joining the PhpStorm team we want to experiment with some new things, so stay tuned!

In this edition, we’ll catch up on the most interesting things that have happened in the PHP world over the last couple of months. As always, it includes curated news, articles, tools, and videos.

News

  • PHP 7.4.29, PHP 8.1.5, and PHP 8.0.18
    These are security releases for Windows users, due to updates of built-in dependencies. For non-Windows users, they are just regular bug-fix updates.For PHP 7.3, updates are no longer released, even for security problems. If you are still using PHP 7.3 or PHP 5.x versions, consider updating as soon as possible.

    The Symfony team has raised its minimum required PHP version to 8.1 in the upcoming Symfony 6.1 release. The same shift was made for Drupal 10 and Laravel 10.

    Also, the recently released Ubuntu 22.04 LTS comes with PHP 8.1 preinstalled.

  • Updates from the PHP Foundation
  • Developer Ecosystem Survey 2022
    The annual survey from JetBrains is now open and, of course, there is a section about PHP. This is what the results from last year look like. Take the survey for a chance to win one of the prizes!
  • News from PHP-FIG
  • PhpStorm 2022.1 released
    It comes with improvements for Blade, WordPress, ArrayShape annotations, and many more. Check out a short What’s New video or read the blog post for the full story.
  • Composer 2.3 Release
    This release brings small improvements for users and a modernized internal codebase.

    There was also a vulnerability discovered recently – CVE-2022-24828: Composer Command Injection. An attacker controlling a Git or Mercurial repository explicitly listed by URL in composer.json could use specially crafted branch names to execute commands on the machine running the composer update.

    Make sure your Composer is up-to-date by running composer self-update.

  • Craft CMS 4
    A major update of the popular open-source CMS was released.

PHP Core

Most of the Core news is covered in detail in the PHP Roundup series from the PHP Foundation, so we’ll only mention them briefly.

Tools

  • CanIPHP.com – It’s like caniuse.com, but for PHP features.
  • clue/stream-filter – A simple and modern approach to stream filtering in PHP. You can do some crazy stuff with stream filters in PHP, but also practical things, too.
  • sfx101/deck – A GUI tool for quick spin-up and configuration of local web development environments, which could be useful for PHP newcomers.
  • marijnvanwezel/try – A simple CLI tool to try Composer packages with a single command. Just install it and run: try %vendor%/%package%.
  • frodeborli/moebius – Golang-like coroutines for PHP versions 8.1 or above. The author used his own event-loop implementation, and even a custom testing framework.
  • Crell/AttributeUtils — Utilities to help ease the parsing and managing of attributes. You might be also interested in koriym/Koriym.Attributes, which can read both doctrine/annotations and PHP 8 attributes with a doctrine annotation interface.
  • spatie/visit – A CLI HTTP client that shows responses of any URL in a beautiful way.
  • laravel/valet – A lightweight local dev environment for Mac. No Docker or VirtualBox, just native Nginx and PHP. It can be used for any projects, not only Laravel, and since v3 you can use different PHP versions for each folder (project).
  • roach-php/core – The complete web scraping toolkit for PHP.
  • PHPStan 1.6.0 – Released with support for conditional return types and integer masks.
  • flow-php/etl – An ETL (Extract Transform Load) data processing library for PHP with support for async processing via ReactPHP or Amphp.
  • igorhrcek/wp-cli-secure-command – One CLI command to secure your WordPress installation.
  • williarin/wordpress-interop – A package based on Doctrine/DBAL for easier access to the WordPress database from other PHP applications.
  • sj-i/php-profiler – A sampling profiler for PHP implemented in pure PHP (FFI). You can generate flame diagrams, run trace output in top-like mode, and more.
  • mrsuh/php-var-sizeof – A function to get the memory size for any variable that promises to be more accurate compared to memory_get_usage(). Requires PHP 7.4 or higher with FFI.
  • davidcole1340/ext-php-rs – Bindings for the Zend API to build PHP extensions natively in Rust.
  • easysoft/phpmicro – A statically compiled micro PHP interpreter that can be bundled with your CLI tools to distribute them as PHP-agnostic binaries. Looking forward to Marcel Pociot automating the process!

Symfony

Laravel

Yii

Misc

Generics

PHP has seen a lot of generics-related activity lately, so we gave them their own section in this post.

Community


That’s all for today – thanks for reading!

If you have any interesting or useful links to share via PHP Annotated, please leave a comment on this post or send me a tweet.

Subscribe to PHP Annotated

Your JetBrains PhpStorm team
The Drive to Develop