Re: [PHP-DEV] [low priority] WeakMaps with scalar keys

2024-07-10 Thread Benjamin Morel
>
> The answer is: it depends. If you don’t need the array to clean up after
> itself, you can indeed use an array of WeakReference to get most of the way
> there. If you want it to clean up after an object gets removed, you either
> need to add support to the stored object’s destructor (which isn’t always
> possible for built-in or final types), or create your own garbage collector
> that scans the array.
>

It is indeed doable in userland using WeakReferences, with a small
performance penalty:

```
class ReverseWeakMap implements Countable, IteratorAggregate, ArrayAccess
{
/**
 * @var array
 */
private array $map = [];

public function count(): int
{
foreach ($this->map as $value => $weakReference) {
if ($weakReference->get() === null) {
unset($this->map[$value]);
}
}

return count($this->map);
}

public function getIterator(): Generator
{
foreach ($this->map as $value => $weakReference) {
$object = $weakReference->get();

if ($object === null) {
unset($this->map[$value]);
} else {
yield $value => $object;
}
}
}

public function offsetExists(mixed $offset)
{
if (isset($this->map[$offset])) {
$object = $this->map[$offset]->get();

if ($object !== null) {
return true;
}

unset($this->map[$offset]);
}

return false;
}

public function offsetGet(mixed $offset): object
{
if (isset($this->map[$offset])) {
$object = $this->map[$offset]->get();

if ($object !== null) {
return $object;
}

unset($this->map[$offset]);
}

throw new Exception('Undefined offset');
}

public function offsetSet(mixed $offset, mixed $value): void
{
$this->map[$offset] = WeakReference::create($value);
}

public function offsetUnset(mixed $offset): void
{
unset($this->map[$offset]);
}
}
```

Now that I think about it, it might be simpler to add an “onRemove()”
> method that takes a callback for the WeakReference class.
>
> — Rob
>


A callback when an object goes out of scope would be a great addition to
both WeakReference & WeakMap indeed, it would allow custom userland weak
maps like the above, with next to no performance penalty!

- Benjamin


Re: [PHP-DEV] Add bcdivmod() to BCMath

2024-06-25 Thread Benjamin Morel
>
> I see, I understand.
>
> But I don't think that's wise. For example, if we reversed the order of
> the div and mod, there would be no cache and we wouldn't get the speed
> boost. (Or does it cache the quotient as well?)
>

I don't think the cache is a good idea either, for the reasons you
mentioned.

I predicted this would probably be on the agenda. Another idea is to pass
> arguments by reference, like in `exec()`.
>
> Personally, I find something like a tuple easier to use. However, without
> generics, all we know is that the return type is an array, which may be
> inconvenient in terms of IDE completion, etc.
>

As for tuple vs reference, I think the general direction is to move away
from references as much as possible, and AFAIK references actually make
things harder for IDEs and static analysis tools, whereas the tuple syntax
array{string, string} is well understood at least by PhpStorm, Psalm and
PHPStan, which can correctly type the function's return value in their
stubs.

— Benjamin


Re: [PHP-DEV] Add bcdivmod() to BCMath

2024-06-25 Thread Benjamin Morel
Hi,

I've been working on improving performance of BCMath lately, and I found
> that I can get the div and mod in one calculation. This is obviously faster
> than calculating it twice separately.
>
> Do you think there's a demand for this feature?
>
> e.g.
> ```
> [$quot, $rem] = bcdivmod('123', '2');
> // $quot is '61', $rem is '1'
> ```
>
> The naming and return value scheme is inspired by Python and Ruby.
>
> Of course, if this is added, equivalent functionality will be added to the
> Number class.
>
> Regards,
>
> Saki
>

I would definitely use this in brick/math:

https://github.com/brick/math/blob/0.12.1/src/Internal/Calculator/BcMathCalculator.php#L43-L49


> This isn't something I'm likely to ever use as I don't do complex math
> much, but it seems like a reasonable optimization for those that do.  No
> objection.
>
> My only question is the pseudo-tuple return, which is rarely used in PHP
> (although I've used it myself, I think exactly once), and I think this
> would be the first use of it in a built in library.  (I may be wrong on
> that.)  I don't have a particular alternative to suggest, just flagging
> that as the main part that could warrant discussion.
>
> --Larry Garfield
>

It's actually already used by gmp_div_qr(), so +1 from me.

- Benjamin


Re: [PHP-DEV] [RFC] [Vote] Type Guards for Classes

2024-05-16 Thread Benjamin Morel
On Thu, 16 May 2024 at 22:33, Patrik Václavek  wrote:

> Introduction
> *
>
> This RFC proposes a new feature in PHP: type guards for classes (or
> interfaces). This feature aims to simplify and standardize the process of
> verifying that a variable is an instance of a specific class, enhancing
> code readability and reducing boilerplate code.
>

Hi, please see this discussion:
https://externals.io/message/105332

In particular this comment from Nikita:
https://externals.io/message/105332#105348

That being said, I would still love it if we could find a way to get this
feature, under this syntax or another, into PHP!

- Ben


Re: [PHP-DEV] Two new functions array_first() and array_last()

2023-10-18 Thread Benjamin Morel
On Wed, 18 Oct 2023 at 17:47, Levi Morrison 
wrote:

>
> I don't see how `array_is_list` is relevant to `array_first` and
> `array_last`. PHP arrays are ordered:
>
> $foo = [
> "first" => 1,
> "third" => 3,
> ];
>
> It would be perfectly fine to use `array_first` or `array_last` with
> `$foo`. I think probably you would use `array_key_first` and
> `array_key_last` so you also get the key and not just the value, but I
> don't see any need to reduce `array_first` and `array_last` to only be
> logical or correct with arrays that uphold `array_is_list`.
>

I didn't mean that array_first/last should only work on lists; they should
work on any array as you mentioned. I was just correcting a statement about
lists.
Sorry if I wasn't clear.

- Benjamin


Re: [PHP-DEV] Two new functions array_first() and array_last()

2023-10-18 Thread Benjamin Morel
On Wed, 18 Oct 2023 at 17:05, Robert Landers 
wrote:

>
> This is simply not true, 0 is not always the first key in a list,
> especially after filtering it. Hence there is a need for this function
> in the first place.


Just to clarify this point: If 0 is not the first key, then it's not a list.
After filtering a list, you get an array that may or may not be a list:
https://3v4l.org/VegUr


Regardless, to add my 2 cents, I'd keep things simple and vote for this
signature:

array_first(array $array): mixed
array_last(array $array): mixed

returning the first/last element, or `null` if the array is empty.


Or, alternatively:

array_first(array $array, mixed $default = null): mixed
array_last(array $array, mixed $default = null): mixed

returning `$default` if the array is empty.
Both look fine to me.

- Benjamin


Re: [PHP-DEV] Previous discussions about generics syntax only?

2023-10-16 Thread Benjamin Morel
Hi, yes there was, back in 2020: https://externals.io/message/111875

- Benjamin

On Mon, 16 Oct 2023 at 16:08, Olle Härstedt  wrote:

> Hello internals,
>
> Was there a previous discussion about the pros/cons of adding only the
> syntax needed for generics, but not the functionality? So static
> analyzers could use it, instead of docblocks. I looked at externals.io
> but couldn't find anything specific.
>
> Regards
> Olle
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Reflection*::hasAttribute()

2023-07-12 Thread Benjamin Morel
>
> I think that would require an RFC.
>
> To clarify, you're proposing to replace this:
>
> count((new ReflectionClass(Beep::class))->getAttributes(Ignore::class)) ==
> true
>
> with
>
> (new ReflectionClass(Beep::class))->hasAttribute(Ignore::class)
>
> Right?  That doesn't seem like a huge improvement.
>
> --Larry Garfield



Actually,

if ((new ReflectionClass(Beep::class))->getAttributes(Ignore::class))

would work as well, so basically:

$rc->hasAttribute(Ignore::class) === (bool)
$rc->getAttributes(Ignore::class);

- Benjamin

>


Re: [PHP-DEV] Possible RFC: PDOStatement::addBatch

2023-06-14 Thread Benjamin Morel
On Wed, 14 Jun 2023 at 01:41, Vinicius Dias  wrote:

> Hello, folks. I hope you all are well.
>
> I was talking to friend about a feature I would like to see in PHP but
> I mentioned that unfortunately I do not have the knowledge to try
> implementing it myself, since it is not something very simple, so he
> mentioned that I could bring this discussion up to this list and see
> if there would be a person willing to develop that.
>
> The feature is a new method in PDOStatement called addBatch to allow
> batch INSERTs, exactly like Java's JDBC[1] has. This method would
> allow us having one single INSERT SQL query, adding multiple values to
> it, and sending this to the database at once, as one single query.
>


Hi Vinicius,

For what it's worth, this is somehow possible in userland by using
concatenated queries and PDOStatement::nextRowset():

```
$statement = $pdo->prepare('
SELECT ?;
SELECT ?, ?;
SELECT ?, ?, ?;
');

$statement->execute([
'one',
'two', 'three',
'four', 'five', 'six'
]);

do {
print_r($statement->fetchAll(PDO::FETCH_ASSOC));
} while ($statement->nextRowset());
```

Please note that this will only work with PDO::ATTR_EMULATE_PREPARES set to
true (default value), so this is of (very) limited use, as it's most likely
still sent to the db as individual queries.
Plus it comes with potential caveats regarding concatenating queries, as
implied by Kamil.

If batching was native to PDO, and brought performance improvements (making
less round trips to the database), I'd be all for it.

In the meantime, if you just want to speed up consecutive INSERT
statements, you might want to use extended inserts instead:

INSERT INTO table (a, b) VALUES (1, 2), (3, 4), (5, 6);

I have a library that abstracts this for you, if that helps:
https://github.com/brick/db

- Benjamin


Re: [PHP-DEV] Proposal: native decimal scalar type support

2023-04-26 Thread Benjamin Morel
Le mer. 26 avr. 2023 à 12:29, Alexander Pravdin  a
écrit :

> As a user, I want to have native decimal scalar type support.
>


For what it’s worth, this is already solved in userland:
https://github.com/brick/math

Now having always-available support for arbitrary precision math in the
language, without having to install ext-gmp or ext-bcmath, would definitely
be a plus. Currently, brick/math can fallback to pure PHP calculations, but
with a severe performance hit.

- Benjamin


Re: [PHP-DEV] ReflectionType for iterable / PHP 8.2

2022-11-02 Thread Benjamin Morel
>
> > That's a intentional behaviour change and related to this accepted PHP
> 8.2 RFC: https://wiki.php.net/rfc/iterator_xyz_accept_array
> >
> > Smile,
> > Juliette
>
> It is rather related the following RFC:
>
> https://wiki.php.net/rfc/dnf_types
>
> The change was discussed in this thread:
>
> https://externals.io/message/117577
>
> —Claude


Thanks to both of you, if this change is expected then I'll adjust my code
accordingly.

Benjamin


[PHP-DEV] ReflectionType for iterable / PHP 8.2

2022-11-02 Thread Benjamin Morel
Hi internals,

It just came to my attention that there is a change of behaviour between
PHP 8.1 and 8.2 in the way iterable is decomposed, or not, into
Traversable|array when reflected:

```
function foo(): iterable {}
function bar(): stdClass|iterable {}

echo (new ReflectionFunction('foo'))->getReturnType(), PHP_EOL;
echo (new ReflectionFunction('bar'))->getReturnType(), PHP_EOL;
```

Output on PHP 8.1:

```
iterable
stdClass|iterable
```

Output on PHP 8.2:

```
iterable
stdClass|Traversable|array
```

Is this expected behaviour? Or should I file a bug? I'm particularly
surprised that it behaves this way on PHP 8.2 only in the presence of union
types.

Thank you,
Benjamin


Re: [PHP-DEV] DB specific PDO subclasses questions.

2022-06-06 Thread Benjamin Morel
On Mon, 6 Jun 2022 at 21:15, Dan Ackroyd  wrote:

2. Other than the SQLite blobOpen functionality, does anyone know of
> any other functionality that is exposed by SQLite or Postgres that
> isn't currently exposed through the magic PDO methods?
>

Hi, what about the ability to load an extension on SQLite?
https://bugs.php.net/bug.php?id=64810
Basically the equivalent of SQLite3::loadExtension()


- Benjamin


Re: [PHP-DEV] Re: Array comparison works completely different than documented?

2021-12-01 Thread Benjamin Morel
>
> The point is that $a > $b is actually checking whether $b <= $a.  This
> is fine for ordered values, but these arrays are not orderable
> (according to PHP's comparison).  That might indeed not be documented in
> the PHP manual (the language specification appears to be abandoned anyway).


Shouldn't we throw an exception when comparing arrays with <, <=, >, >=
anyway?

- Benjamin


Re: [PHP-DEV] Change of $depth behaviour in json_encode() on PHP 8.1

2021-10-17 Thread Benjamin Morel
>
>
> This is a bug. Please report it on https://bugs.php.net/
>
> See https://3v4l.org/vFgh0
>
> https://github.com/php/php-src/commit/f9f8c1c79cac1b03279190e0c5513a51881615f9
> https://github.com/php/php-src/pull/6811
>
> Best Regards,
> Kamil
>

Thank you! Reported as https://bugs.php.net/bug.php?id=81532


[PHP-DEV] Change of $depth behaviour in json_encode() on PHP 8.1

2021-10-17 Thread Benjamin Morel
Hi internals,

I noticed a change of behaviour on PHP 8.1:

https://3v4l.org/DoG4A

```
// depth 1
$a = new \stdClass();

// depth 2
$b = new \stdClass();
$b->x = $a;

// depth 3
$c = new \stdClass();
$c->x = [$a];

var_export(json_encode($a, 0, 0)); echo "\n";
var_export(json_encode($b, 0, 1)); echo "\n";
var_export(json_encode($c, 0, 2));
```

On PHP 8.1, all three examples successfully encode the input object, while
on PHP <= 8.0, json_encode() returns false as this exceeds the max depth.

I couldn't find a note about this in the migration guide for PHP 8.1. Is
this documented, or is this a regression that should be fixed?

Thanks in advance,
— Benjamin


Re: [PHP-DEV] Order of properties in (array) cast on PHP 8.1

2021-10-13 Thread Benjamin Morel
>
> Yes, this change is expected and documented, see:
>
> https://www.php.net/manual/en/migration81.other-changes.php#migration81.other-changes.functions.core
>

Thanks for the pointer!
And sorry for the noise.

— Benjamin


[PHP-DEV] Order of properties in (array) cast on PHP 8.1

2021-10-13 Thread Benjamin Morel
Hi internals,

While running the test suite of one of my libs against PHP 8.1, I noticed
that the order in which properties are returned in an (array) cast has
changed.

For example when casting an instance of this class to array:

class A
{
private $x = 'x';
}

class B extends A
{
public $y;
public $z;
}

On PHP 7.4-8.0, $x is returned last, while on PHP 8.1, it is returned first.

Demo: https://3v4l.org/FTMki

It's not a big deal, but before I change my test suites, I wanted to double
check here if this change was expected?

Thanks in advance,
— Benjamin


Re: [PHP-DEV] DateTimeZone silently falls back to UTC when providing seconds

2021-09-11 Thread Benjamin Morel
>
> >Before doing so, shouldn't we discuss whether it makes sense to accept
> >a
> >time-zone offset with seconds, when the granularity seems to be 15
> >mins?
> >
> >https://en.wikipedia.org/wiki/List_of_UTC_time_offsets
> >
> >— Benjamin
>
> No need. Early timezone offsets in the timezone database are in LMT (local
> mean time), which have second granularity.
>
> cheers,
> Derick


Hi, sorry for resurrecting an old thread, but now that this bug
 has been fixed in PHP 8.0.10, I can
see that seconds have been forbidden from DateTimeZone altogether:

https://3v4l.org/QpSln

Before forbidding seconds in brick/date-time's *TimeZoneOffset* as well
(and going against JSR-310, which this library was derived from), can I
please know why this decision was made, when as I understand it, this goes
against your statement above?

Thanks in advance,
- Benjamin


Re: [PHP-DEV] Alias stdClass to DynamicObject?

2021-09-06 Thread Benjamin Morel
Hi Nikita, Rowan,

In the thread for deprecation of dynamic properties, Rowan suggested that
> we alias "stdClass" to "DynamicObject" in
> https://externals.io/message/115800#115802. I wanted to split this
> discussion off into a separate thread, as this can be decided
> independently.
>
> The rationale for this is that "stdClass" is something of a misnomer: The
> name makes it sound like this is a common base class, as used in a number
> of other languages. However, PHP does not have a common base class. The
> only way in which "stdClass" is "standard" is that it is the return type of
> casting an array to (object).
>
> The actual role of stdClass is to serve as a container for dynamic
> properties, thus the suggested DynamicObject name.
>
> What do people think about adding such an alias? Is this worthwhile?


Yes, please! A future where dynamic properties are only allowed on
DynamicObject is bright.

I would even deprecate the stdClass alias straight away, so that the whole
thing can be gone in PHP 9.

Kind regards,
Benjamin

>


Re: [PHP-DEV] Request for karma to vote on RFCs

2021-07-19 Thread Benjamin Morel
>
> I know I’m not a “project leader” for any of the handful large PHP
> projects. I also know that I am far from the “top 1000 best developers”
> list. But I know that there are not many people (if any) that have a larger
> impact of user-land PHP right now.
>
> (I do acknowledge that there are people with more impact over the Symfony
> community, the Laravel community, or the cool async community etc.)
>
> The only thing I’m asking for is to be among those 1000+ people that can
> vote on the language’s future.
>
> // Tobias
>


There was a discussion a year ago
 about giving userland library
maintainers the right to do a semi-official vote, that would be non-binding
as far as the RFC is concerned, but would give people with RFC vote karma a
good idea of what the most influential userland library maintainers think
of a change in the language, so that they can take this variable into
account prior to voting themselves.

As a library author with 4 million downloads per month, it also crossed my
mind to request a right to vote on RFCs, but given previous discussions on
the topic, I understood that core maintainers are reluctant to give voting
rights to userland developers, whatever their influence, so I've restrained
myself from doing so so far.

I do understand the concern from core maintainers that if people voting on
RFCs are not the ones getting their hands dirty maintaining the codebase,
it can quickly become an issue. I would, however, strongly advise core
maintainers to consider the idea of performing an "official" library
maintainers vote before the actual vote takes place.

At the end of the day, we'll be the ones maintaining libraries that use
these new PHP features, that will have to provide compatibility for
multiple versions of PHP, etc. It would be nice if we could at least
formally give our opinion on each individual RFC. Yes, we can do so via the
mailing list, but this is just one message lost in the middle of a usually
verbose discussion, which is often discouraging to say the least.

— Benjamin


Re: [PHP-DEV] [RFC] [VOTE] is_literal

2021-07-18 Thread Benjamin Morel
>
> There's some BC-breaks to be aware of when switching emulated prepares.
> One example I know of is that when using emulated prepares you can reuse
> the same placeholder (as in the following example), but with emulated
> prepares disabled this does not work.
>
> $sql = "SELECT * FROM table WHERE column1 LIKE CONCAT('%', :searchValue,
> '%') OR column2 LIKE CONCAT('%', :searchValue, '%');";
> $params = [
>  "searchValue" => "test",
> ];
>

This, and do note that from a performance point of view, disabling emulated
prepares is not innocuous : most of the time, you effectively send twice as
many queries to the database : one prepare, one execute.
There is a *small* performance improvement in using prepared statements if
you're executing the same statement many times; but in all other cases,
you're spending twice as much time waiting for the database.

Are there documented SQL injection opportunities when using emulated
prepares? I'm not aware of any.

— Benjamin


Re: [PHP-DEV] Type casting syntax

2021-07-10 Thread Benjamin Morel
> I've been thinking about extending PHP's cast syntax to user-defined types,
> e.g. not only (int)$foo but also (MyClass)$foo. Currently, a T_STRING in
> parentheses is always treated as a constant - would it be acceptable to
> hijack this syntax when used in unary operation context, i.e. "(" T_STRING
> ")" expr? If not, any other alternatives?


Hi, I proposed something similar a while back, you might want to have a
look at this discussion:

https://externals.io/message/105332#105367

- Benjamin


Re: [PHP-DEV] [RFC] is_trusted - was is_literal

2021-06-21 Thread Benjamin Morel
On Tue, 22 Jun 2021 at 01:06, Derick Rethans  wrote:

> On 21 June 2021 23:37:56 BST, Yasuo Ohgaki  wrote:
> >
> >The name "is_trusted" is misleading.
> >Literal is nothing but literal.
>
> I agree with this. The name is_trusted is going to be the same naming
> mistake as "safe mode" was. Developers will put their trust in it that it
> is 100% guaranteed safe.


FWIW, agreed, too. Trusted is vague and may imply some false sense of
security. Literal is literally what it says on the tin.

— Benjamin


Re: [PHP-DEV] DateTimeZone silently falls back to UTC when providing seconds

2021-05-30 Thread Benjamin Morel
>
> I can't think of why this couldn't work. Duke a bug report please at
> bugs.php.net?


 Before doing so, shouldn't we discuss whether it makes sense to accept a
time-zone offset with seconds, when the granularity seems to be 15 mins?

https://en.wikipedia.org/wiki/List_of_UTC_time_offsets

— Benjamin


[PHP-DEV] DateTimeZone silently falls back to UTC when providing seconds

2021-05-30 Thread Benjamin Morel
Hi internals,

An issue  was brought up on
my date-time library, that boils down to the fact that DateTimeZone
silently falls back to UTC when providing an offset with seconds:

(new DatetimeZone('+01:45:30'))->getName(); // 00:00

https://3v4l.org/9ZrK6

If this is unsupported (this would make sense), should it throw an
exception instead?

Thank you for your time.

⁠— Benjamin


Re: [PHP-DEV] Allow commit() without transaction?

2021-04-12 Thread Benjamin Morel
>
>
> I think it is really nice that commit() throws for inactive
> transactions. Code paths that mess up your transactions will not go
> unnoticed that easily.
>

+1. I've always found this behaviour in MySQL very surprising and error
prone (BEGIN; BEGIN; COMMIT; COMMIT; => no errors), and I'm actually very
happy to see this solved at PDO level.

IMO if someone relies on commit() not throwing if there is no active
transaction, they should be the one doing the extra check: if
($pdo->inTransaction()) $pdo->commit().

— Benjamin


[PHP-DEV] Required parameter after optional one

2021-04-09 Thread Benjamin Morel
Hi internals,

I'm wondering why PHP 8 started warning about required parameters declared
after optional ones, when this version is the one that also introduced
named parameters, which can take advantage of this:

```
function test($a = 1, $b) {
echo $a, $b;
}

test(b: 2);
```

> Deprecated: Required parameter $b follows optional parameter $a in
/in/DmhYG on line 3
> 12

https://3v4l.org/DmhYG

If I'm not mistaken, the introduction of this warning (January 2020
) predates the introduction of named
parameters (May 2020 ), which could
explain why it would have temporarily made sense to introduce this warning.

Shouldn't it be removed now, that it makes IMO full sense with named
parameters to have required and optional parameters at arbitrary positions?

Thank you for your time,

— Benjamin


[PHP-DEV] Re: Changes to Git commit workflow

2021-03-29 Thread Benjamin Morel
>
> Hi everyone,
>
> Yesterday (2021-03-28) two malicious commits were pushed to the php-src
> repo [1] from the names of Rasmus Lerdorf and myself. We don't yet know how
> exactly this happened, but everything points towards a compromise of the
> git.php.net server (rather than a compromise of an individual git
> account).
>

That is scary. Can you disclose the contents of the commits? Are they
specially designed to open a security hole, or to be harmful in another way?


> While investigation is still underway, we have decided that maintaining
> our own git infrastructure is an unnecessary security risk, and that we
> will discontinue the git.php.net server. Instead, the repositories on
> GitHub, which were previously only mirrors, will become canonical. This
> means that changes should be pushed directly to GitHub rather than to
> git.php.net.
>

This change will be welcome anyway!

— Benjamin


Re: [PHP-DEV] What should we do with utf8_encode and utf8_decode?

2021-03-21 Thread Benjamin Morel
On Sun, 21 Mar 2021 at 15:18, Rowan Tommins  wrote:

> I can see three ways forward:
>
> A) Raise a deprecation notice in 8.1, and remove in 9.0. Do not provide
> a specific replacement, but recommend people look at iconv() or
> mb_convert_encoding(). There is precedent for this, such as
> convert_cyr_string(), but it may frustrate those who are using the
> functions correctly.
>
> B) Introduce new names, such as utf8_to_iso_8859_1 and
> iso_8859_1_to_utf8; immediately make those the primary names in the
> manual, with utf8_encode / utf8_decode as aliases. Raise deprecation
> notices for the old names, either immediately or in some future release.
> This gives a smoother upgrade path, but commits us to having these
> functions as outliers in our standard library.
>

Hi, I'm personally fine with A or B, both of which have pros & cons:

- A is probably the cleanest way as, as you said, these functions should
never have existed (locked to a single encoding that will only benefit a
portion of users), but that's quite a BC break
- B has is less of a BC break as it gives users a chance to rename their
function calls, but leaves an oddity in the standard library

I'm a bit worried that either way, we'll start seeing some "polyfills"
appear on Packagist to re-introduce the old functions, but at least they
will be gone from the core.

— Benjamin


Re: [PHP-DEV] PDO::PARAM_INT and pgsql driver

2021-03-21 Thread Benjamin Morel
> >> Is there any reason why the pgsql driver doesn't respect PDO::PARAM_STR?
> >
> > Looks like a bug to me. I thought this had been fixed a while back, but
> > apparently it wasn't. I'll try to find some time to investigate in the
> > next few days.
>
> Looks like the problem is in
> <
> https://github.com/php/php-src/blob/php-7.4.16/ext/pdo_pgsql/pgsql_statement.c#L377-L391
> >


I've opened a bug report to keep track of it:
https://bugs.php.net/bug.php?id=80892

Thank you,
Benjamin


[PHP-DEV] PDO::PARAM_INT and pgsql driver

2021-03-14 Thread Benjamin Morel
Hi internals,

I just stumbled upon what I consider to be a bug with the PDO pgsql driver.
*TL;DR: the driver treats parameters bound with PARAM_INT the same as
PARAM_STR.*

Take the following example:

```
$pdo = new PDO('pgsql:host=localhost;port=5432', 'postgres', 'postgres');

$statement = $pdo->prepare("
SELECT ST_AsText(
ST_Transform(
ST_GeomFromText('POINT(0 0)', 2154),
?
)
)
");

$statement->bindValue(1, 4326, PDO::PARAM_INT);
$statement->execute();
```

This fails with the following message:

PDOException: SQLSTATE[XX000]: Internal error: 7 ERROR: could not parse
> proj string '4326'


This is because the pgsql driver seems to treat everything as PARAM_STR,
despite being explicitly requested to bind the value as PARAM_INT; the
placeholder is therefore replaced with the string '4326' instead of the
integer 4326.

The problem is, in PostGIS, the ST_Transform()
 function has different
signatures with different behaviours depending on whether the second
parameter is an integer or a string.

As far as I can see, because of this issue, *there is no way to pass an
actual integer to ST_Transform()*, which forces me to use
PostgreSQL-specific cast syntax to get the behaviour I need, in a library
 I maintain that's supposed to work with any
GIS-enabled database.

Is there any reason why the pgsql driver doesn't respect PDO::PARAM_STR?

I asked this question on StackOverflow
, and was pointed to the
following bug, which I'm not sure is directly related, but was closed as
"not a bug":

https://bugs.php.net/bug.php?id=50206

*Should this be requalified as a bug and be fixed?*

Thanks in advance for your consideration,

— Benjamin


Re: [PHP-DEV] [RFC] Namespaced in bundled extensions

2021-02-26 Thread Benjamin Morel
>
> Maybe off-topic, but I don't think you could "fix" them:
> for array_map, the array is variadic-like, so must be last;
> for array_filter, the callback is optional, so must be after the array.
> (Correct me if I'm wrong.)
>
> --
> Guilliam Xavier
>

Good point. Then that would be an opportunity to question whether
array_map() is doing too much, and should just work on a single array.
Like Array.map()

in JS, Stream.map()

in Java, Iterator.map()
 in
Rust, etc.

— Benjamin


Re: [PHP-DEV] [RFC] Namespaced in bundled extensions

2021-02-26 Thread Benjamin Morel
Thank you for this RFC, Nikita. This is a necessary first step in the right
direction.

Even though this is out of scope for this RFC, I hope that moving standard
functions to namespaces will be an opportunity to fix inconsistencies in
parameter order, like:

array_map($callback, array)
array_filter($array, $callback)

and not just an alias under a namespace!

 — Benjamin

On Thu, 25 Feb 2021 at 21:26, Nikita Popov  wrote:

> Hi internals,
>
> The question of namespaces in the stdlib has been coming up a lot recently,
> so I'd like to present my own stab at resolving this question:
>
> https://wiki.php.net/rfc/namespaces_in_bundled_extensions
>
> Relative to a number of previous (declined) proposals, the main difference
> is that I do not propose a top-level "PHP\" vendor namespace, and instead
> recommend the use of "ExtName\", in line with existing practice for
> extensions. I believe this addresses the primary concern with previous
> proposals.
>
> Regards,
> Nikita
>


Re: [PHP-DEV] Re: [VOTE] Enumerations

2021-02-17 Thread Benjamin Morel
Congratulations  and thank you Larry and Ilija, this will be a great
addition to PHP!

— Benjamin

On Wed, 17 Feb 2021 at 15:31, Larry Garfield  wrote:

> On Wed, Feb 3, 2021, at 11:28 AM, Larry Garfield wrote:
> > The vote on the Enumerations RFC is hereby opened.  It will run until
> > 17 February 2021.
> >
> > https://wiki.php.net/rfc/enumerations
> >
> > Vote now, or forever hold your memory allocations.
>
>
> The Enum vote has now closed.  Final results:
>
> For: 44
> Against: 7
> Approval rate: 86%
>
> The Enum RFC has been approved.  Ilija is still fixing up some bugs and
> edge cases in the code itself but it should be merged soon.
>
> Thank you to everyone for your feedback, support, and votes over the past
> few weeks!  I would enumerate you all individually, but there's a lot of
> you and it would take up a lot of memory... :-)
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Warning for implicit float to int conversions

2021-02-05 Thread Benjamin Morel
On Sat, 6 Feb 2021 at 00:46, David Gebler  wrote:

> Generating a warning on explicit casts of (non-integer) floats to int
> would IMO make no sense at all, it would put PHP at odds with other major
> languages such as C, Python and Java and go against normal, reasonable
> expectations of how a programming language behaves.
>
> You said in an earlier comment "it's better to be explicit about your
> intent", but doing something like (int)3.5 *is* being explicit about your
> intent - and truncating casts on float to int is the widely established
> norm.
>
> This was exactly my reservation about deprecating this behaviour even as
> an implicit cast - in my mind it isn't a bug or flaw, it's there by design.
>
> If developers want to round/ceil/floor/do whatever with a float prior to
> using it as an int, they already have that option and the greatest
> flexibility.
>
> At least with the implicit case, I understand the motivation and argument
> for bringing coercion more in line with strict typing behaviour and
> catching cases where such a cast may not have been intentional (though I
> still think a warning is too high an error level for this and would favour
> a notice or deprecation, were it to be done at all).
>

Let's agree to disagree on what would be the ideal behaviour of type casts.
I do understand that it would be a big concern for BC if (int) stopped
working for floats with a fractional part.

Could we at least fix the odd cases where the cast is definitely a failure?
Like:

(int) 1e60; // 0
(int) "foo"; // 0

— Benjamin


Re: [PHP-DEV] Inheritance Cache

2021-02-05 Thread Benjamin Morel
On Fri, 5 Feb 2021 at 15:03, Dmitry Stogov  wrote:

> Hi,
>
> I'm glad to present the result of my recent work - Inheritance Cache.
>
> https://github.com/php/php-src/pull/6627
>
> This is a new transparent technology that eliminates overhead of PHP class
> inheritance.
>
> PHP  classes are compiled and cached (by opcahce) separately, however their
> "linking" was done at run-time - on each request. The process of "linking"
> may involve a number of compatibility checks and borrowing
> methods/properties/constants form parent and traits. This takes significant
> time, but the result is the same on each request.
>
> Inheritance Cache performs "linking" for unique set of all the depending
> classes (parent, interfaces, traits, property types, method types involved
> into compatibility checks) once and stores result in opcache shared memory.
> As a part of the this patch, I removed limitations for immutable classes
> (unresolved constants, typed properties and covariant type checks). So now
> all classes stored in opcache are "immutable". They may be lazily loaded
> into process memory, if necessary, but this usually occurs just once (on
> first linking).
>
> The patch shows 8% improvement on Symphony "Hello World" app.
>
> I'm going to merge this patch into master on next week.
> Please review and give your comments.
>
> Thanks. Dmitry.
>

Hi Dmitry, that sounds awesome, congrats for this work!
If I understand correctly, this only offers performance improvements when
the classes are not preloaded, and thus closes a bit the gap between
preloading on & off?

— Benjamin


Re: [PHP-DEV] [RFC] Warning for implicit float to int conversions

2021-02-05 Thread Benjamin Morel
On Fri, 5 Feb 2021 at 11:56, AllenJB  wrote:

> (And after checking the manual, I'd also note here that round() also
> returns a float, so how exactly does your example here work? Is it only
> OK to explictly cast a float that's the return value of a function? Or
> only explictly cast a float if the fractional part is .0? Is that viable
> given the "inaccuracy" of floats? Or would it be better for PHP to have
> some non-range/accuracy-sensitive representation for integers (and
> decimals) here?) (and now we're getting into "why are we still using
> floating point math by default in 2021" territory, so I'll stop right here)
>

Floats (doubles) can accurately represent all integers up to 2⁵³, so there
is no inaccuracy in this range; the result from round() or floor() could
therefore be safely passed to (int) even if the cast operator checked for a
0 fractional part, which is what I'm advocating for.

There are legitimate cases for explicitly casting floats to int. For
> example floor() outputs a float, but in the context of the domain I'm
> working I might know that the result is never going to exceed a certain
> value and want the result explicitly as an int.


Perfect, so (int) floor() would work wonders for you, even with the strict
casting I'm talking about.
And if the result does overflow an integer one day, I'm sure you'd be happy
to know it by getting an exception, rather than getting silently ZERO:

echo (int) 1e60; // 0

— Benjamin


Re: [PHP-DEV] [RFC] Warning for implicit float to int conversions

2021-02-04 Thread Benjamin Morel
On Thu, 4 Feb 2021 at 17:05, G. P. B.  wrote:

> Greetings internal,
>
> I'm proposing a new RFC which would warn when an implicit conversion
> from float to int occurs.
>
> The draft is currently located on GitHub:
> https://github.com/Girgias/float-int-warning/
> for ease of commenting/providing changes to it.
>
> The official discussion phase wouldn't start before I convert it to docwiki
> and
> post it on the wiki, something I'm planning to do next week.
>
> Any feedback is appreciated.
>
> Best regards,
>
> George P. Banyard
>

Hi George,

Thank you for this proposal, I'm all for it, though I'd go one step
further, and actually issue a warning during explicit casting as well:

(int) 3.5; // E_WARNING
(int) round(3.5); // OK

In my experience, it's better to be explicit about your intent, so forcing
the user to round() before casting when the float has a fractional part is
OK to me.
This would help prevent weird silent conversions such as when you cast to
(int) from user input:

$age = $_GET['age']; // '25.75'
$x = (int) $foo; // I'd expect a warning, not a silent conversion to 25

— Benjamin


Re: [PHP-DEV] password_verify() and unknown algos

2021-01-29 Thread Benjamin Morel
Hi all, thanks for the constructive feedback.

On Fri, 29 Jan 2021 at 15:52, Marco Pivetta  wrote:

>
> Gonna be the usual person saying: let's not clutter functions with more
> behavior than what's needed :-)
>
> If you need to validate a hash for being "well formed" rather than
> "matching", then write a separate function dedicated to that, rather than
> increasing the complexity of a pre-existing symbol.
>
> Marco Pivetta


I would definitely vote for that, too. It feels to me like throwing an
exception on invalid algo / malformed hash should be the default behaviour,
and that the use case brought up by Anthony, although very relevant, should
be the one that should test for validity using another function (or pass an
extra parameter).

That being said, it's indeed a BC break. Would it be small enough to be
allowed to hit 8.1? I don't know.

— Benjamin


[PHP-DEV] password_verify() and unknown algos

2021-01-27 Thread Benjamin Morel
Hi internals,

I just spent some time debugging an authentication issue after upgrading
PHP, and realized that it was due to ext-sodium not being installed, so
password_verify() would always return false for argon2i hashes.

Digging a bit more, I realized that password_verify() does not complain if
the algorithm is unknown, or if the hash string is malformed:

var_export(password_verify('passw0rd', 'any/string%as|a$hash')); //
false

Shouldn't it throw an exception, or a least trigger a warning, when the
algorithm is unknown, or the hash is malformed? Returning false IMO, should
mean "I recognize this hash, but it doesn't match your password". "I don't
recognize this hash" is an application issue and should be reported.

What do you think?

— Benjamin


Re: [PHP-DEV] [RFC]: Change Default mysqli Error Mode

2021-01-25 Thread Benjamin Morel
>
> Moreover, I'd rather we get rid of the warning modes all together as they
> make the least sense to me.
> Either you're handling the failures explicitly anyway and you use the
> silent mode, or you don't and want it to throw with the exception mode.
> The warning mode is literally the worst of both worlds, it doesn't fail on
> failure so you need to check for failure manually,
> and you need to suppress the warnings because otherwise you get false
> negatives.
>
> Best regards,
>
> George P. Banyard
>

I'd just like to say amen to that.

Please move as much code as possible to throwing exceptions, and get rid of
warnings. Most of the time when a warning is thrown in PHP, what you
actually want is to deal with it, or stop execution.

- Benjamin


Re: [PHP-DEV] Proposal: short_var_export($value, bool $return=false, int $flags=0)

2021-01-19 Thread Benjamin Morel
> Hi Tyson,
>
> The formatting of var_export is certainly a recurring complaint, and
> previous discussions were not particularly open to changing current
> var_export behavior, so adding a new function seems to be the way to
> address the issue (the alternative would be to add a flag to var_export).
>
> I like the idea of the "one line" flag. Actually, this is the main part I'm
> interested in :) With the one line flag, this produces the ideal formatting
> for PHPT tests that want to print something like "$v1 + $v2 = $v3". None of
> our current dumping functions are suitable for this purpose (json_encode
> comes closest, but has edge cases like lack of NAN support.)
>
> Some note:
>  * You should drop the $return parameter and make it always return. As this
> is primarily an export and not a dumping function, printing to stdout
> doesn't make sense to me.
>  * For strings, have you considered printing them as double-quoted and
> escaping more characters? This would avoid newlines in oneline mode. And
> would allow you to escape more control characters. I also find the current
> '' . "\0" . '' format for encoding null bytes quite awkward.
>  * I don't like the short_var_export() name. Is "short" really the primary
> characteristic of this function? Both var_export_pretty and
> var_export_canonical seem better to me, though I can't say they're great
> either. I will refrain from proposing real_var_export() ... oops :P
>
> Regards,
> Nikita
>

Sorry for the plug, but you may be interested in getting inspiration from
brick/varexporter:

https://github.com/brick/varexporter

In particular:

- uses short array syntax always
- doesn't output array keys for lists
- can output lists of scalars on one line, under a flag:
`INLINE_NUMERIC_SCALAR_ARRAY`

- Benjamin


Re: [PHP-DEV] [RFC] Add is_list(mixed $value): bool to check for list-like arrays

2021-01-05 Thread Benjamin Morel


> I probably brought this up in a previous thread, but I think it's worth
> considering again here, given recent changes to the RFC:
> 
> I think it would make more sense to introduce this as `function
> array_is_list(array $array): bool`. That is, a function that only accepts
> arrays in the first place and determines whether the given array is a list.
> 
> Your RFC does mention this possibility, but I think the argument it makes
> against it is not particularly strong, especially given the recent rename.
> The argument is that is_array_and_list($array) is shorter than writing out
> is_array($array) && array_is_list($array) -- that's still true, but with
> the new name, it's really not that much shorter anymore.
> 
> On the other hand, is_array($array) && array_is_list($array) cleanly
> separates out the two predicates. If we take into account the fact that in
> the vast majority of cases we will know a-priori that the input is an
> array, just not whether it is a list, making the function
> array_is_list($array) is both clearer and more concise.
> 
>function foo(array $array) {
>assert(array_is_list($array)); // Already know it's an array...
>}
> 
>if (is_array($value)) {
>if (array_is_list($value)) { // Already know it's an array...
>return serialize_as_list($value);
>} else {
>return serialize_as_dict($value);
>}
>}
> 
> Regards,
> Nikita

I like array_is_list(array $array): bool much better, too.

- Benjamin

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Enumerations, Round 2

2020-12-30 Thread Benjamin Morel
>
> What's the quickest way (=less code) to have an enum represent it's
> lexical name as the literal values?
>
> So that `… case Foo; case Bar; …` results in `::Foo->value === 'Foo'` etc.?
>
> Is this possible without implementing this manually for all cases?
>
>
AFAICS, you'd need to implement the values manually. The $value property is
only defined on ScalarEnum, not UnitEnum.

- Benjamin


Re: [PHP-DEV] Proposal: Adding SplFixedArray->push() and SplFixedArray->pop()

2020-12-29 Thread Benjamin Morel
On Tue, 29 Dec 2020 at 18:04, tyson andre  wrote:

> Hi Internals,
>
> Currently, PHP doesn't have a built in memory-efficient array type with
> convenient push, pop, and other operations, similar to a list/vector in
> other languages.
> The closest built in in SPL is [SplFixedArray](
> https://www.php.net/manual/en/class.splfixedarray.php)
>
> https://www.php.net/manual/en/class.splstack.php uses a doubly linked
> list, which uses much more memory and time than sequential memory.
>
> Contrary to the name and description in
> https://www.php.net/manual/en/class.splfixedarray.php, the class is
> already resizable.
> The resize method is setSize -
> https://www.php.net/manual/en/splfixedarray.setsize.php
> (increasing size is efficient - erealloc will extend the underlying array
> into free memory if there is nothing in the way)
>
> Many programming languages have a memory-efficient list/vector type that
> can be conveniently appended to and popped from.
>
> https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
> https://www.cplusplus.com/reference/vector/vector/
> https://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-push
>
> Is there any interest in adding this? It would be much more efficient to
> add these in C.
>
> Thanks,
> - Tyson
>

Hi Tyson,

Did you have a look at ext-ds? It provides several very efficient data
structures:
https://github.com/php-ds/ext-ds

I would love if this extension could find its way into core, actually.

Kind regards,
Benjamin


Re: [PHP-DEV] [RFC] Enumerations, Round 2

2020-12-28 Thread Benjamin Morel
Hi Larry, thank you for the updated RFC!
I love it, and having played with the implementation, I can say I love it
so far as well.

I have one suggestion regarding reflection:
Shouldn't ReflectionCase expose an additional getInstance() method, that
would return the case instance, such as Suit::HEARTS?

Also, I noticed 2 typos in the code samples:

- in "Enumerated Methods", 1st code block: missing "implements Colorful"
after "enum Suit"
- in "Enumerated Methods", 2nd code block: missing "public function
color()" after "private function __construct() {}"

Finally, I got a segmentation fault while trying to use what I think is an
unsupported syntax (removing the ":string" from a scalar enum), where is
the correct place to report this? The GitHub PR?

Good luck with the RFC!

- Benjamin

On Mon, 28 Dec 2020 at 21:22, Larry Garfield  wrote:

> Hello, Internalians!
>
> After considerable discussion and effort, Ilija and I are ready to offer
> you round 2 on enumerations.  This is in the spirit of the previous
> discussion, but based on that discussion a great deal has been reworked.
> The main change is that Enumeration Cases are now object instances of the
> Enumeration class rather than their own class.  Most of the other changes
> are knock-on effects of that.
>
> Of particular note:
>
> * Cases may not have methods or constants on them.  They're just dumb
> values.
> * Enums themselves may have methods, static methods, or constants.
> * Traits are supported, as long as they don't have properties.
> * The value() method on scalar enums is now a property.
>
> The full RFC is here, and I recommend reading it again in full given how
> much was updated.
>
> https://wiki.php.net/rfc/enumerations
>
> The implementation is 98% complete; there's still a few lagging bits in
> reflection, and some opcache bugs that Ilija is still stomping on.
>
> There are a few outstanding questions listed that we would like feedback
> on.  We're not entirely certain which direction to go with them, for
> reasons explained in the RFC.  Input on those is especially welcome.
>
> Happy New Year.  May it be enumerable.
>
> --
>   Larry Garfield
>   la...@garfieldtech.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Enumerations

2020-12-09 Thread Benjamin Morel
On Wed, 9 Dec 2020 at 19:48, Mike Schinkel  wrote:

5. Someone else mentioned shortcut syntax, which I would like to mention
> again, although I realize implement details might make this a non-starter.
>
> So if I have a function that accepts a Size from above, e.g.:
>
> function show(Size $size) {}
>
> Then it would be great if we could call the function like this since its
> parameter was type-hinted:
>
> show(::Medium)
>
> Rather than always having to write:
>
> show(Size::Medium)
>
> So can we consider a shortcut syntax?
>

I'm not sure what value a shortcut syntax would bring, but it would surely
break, or at least make ambiguous, union types:

function show(Enum1|Enum2 $value)  {}
show(::Medium)

Which enum would Medium resolve to?

- Benjamin


Re: [PHP-DEV] [RFC] Enumerations

2020-12-05 Thread Benjamin Morel
Thanks a lot for this RFC, Larry and Iliya! I can't imagine the amount of
thought and work put into this.
Enums are definitely a most-wanted PHP feature.

I played a bit with the early implementation, and love it so far. Here are
my thoughts on the RFC and the current implementation:

*Serialization*

I guess what it comes down to is whether / how easily a class can return
> an existing instance when asked to unserialize, rather than setting
> properties on an existing instance. That is, given the string
> "C:4:Suit:6:{Spades}" can the class definition return the appropriate
> singleton for Suits::Spades rather than a newly constructed object?
>
> If this proves tricky to implement, it would probably be better to
> forbid serialization than using the default object format and breaking
> the singleton-ness of the case objects.


+1, totally agree with this statement. That's the first thing I tried when
playing with the implementation, and noticed that serialization is not
supported:

echo unserialize(serialize(Status::Active));
Notice: unserialize(): Error at offset 0 of 42 bytes

I would definitely expect strict equality to be maintained on enum cases
even after unserialization!

*var_export()*

Currently, var_export() returns a __set_state() syntax:

var_export(Status::Active);
Foo\Bar\Status::Active::__set_state(array(
))

I guess this should just return Foo\Bar\Status::Active.

*Scalar Enums, ::cases()*

The implementation does not support these yet, so I haven't had a chance to
play with them.
I share Pierre R.'s concerns, though:

Does this mean that an enum can't have two cases with the same primitive
> value ? I would very much being able to do so, for example, when you
> change a name and want to keep the legacy for backward compatibility.


But I'd understand if you just disallow duplicate scalar values altogether,
this is probably the most sensible solution here.
Another idea that comes to mind is that cases() could return an iterator
instead of an array, having the cases as keys and the scalars as values,
but this would probably come as a surprise and be bad for DX.

*Enum & UnitEnum interfaces*

The implementation does not seem to support these yet. Taking the examples
from the RFC:

Suit::Hearts instanceof Enum; // true => Parse error: syntax error,
unexpected token "enum"
Suit::Hearts instanceof UnitEnum; // true => FALSE


Best of luck with the RFC!
— Benjamin


Re: [PHP-DEV] erorr_reporting() and @ operator

2020-12-02 Thread Benjamin Morel
Thanks for the pointer, Nikita.

I think the updated example (using `error_reporting() & $errno`) fails to
mimic exactly what `error_reporting() === 0` did, though.

Say your php.ini mutes E_WARNING, for example:

error_reporting = E_ALL & ~E_WARNING

Checking for `error_reporting() === 0` allowed to only ignore @-suppressed
statements, but still throw an exception on E_WARNING, ignoring the
error_reporting set in php.ini.

OTOH, checking for `error_reporting() & $errno` still allows to
ignore @-suppressed statements, but **also ignores E_WARNING configured in
php.ini**, which is not always what userland code wants.

I'm not sure how userland code can now replicate the old behaviour, i.e.
specifically detect the @ operator?

— Benjamin


[PHP-DEV] erorr_reporting() and @ operator

2020-12-02 Thread Benjamin Morel
Hi internals,

Since PHP 8.0, `error_reporting()` started returning a non-zero value when
the @ silence operator is used.

Demo: https://3v4l.org/CovYv

Is this intentional? This breaks scripts that converted all errors to
exceptions, except those where the silence operator was used:

set_error_handler(function ($severity, $message, $file, $line) {
if (error_reporting() === 0) {
return;
}

throw new ErrorException($message, 0, $severity, $file, $line);
});

Thank you,
Benjamin


Re: [PHP-DEV] Re: PHP 8 is_file/is_dir input handling

2020-12-01 Thread Benjamin Morel

> Furthermore, Christoph's code uses str_contains() which is only
> available in PHP 8 so it's not a good workaround if PHP 7 and 8 must be
> both supported.
>

Here: https://3v4l.org/LHcmN 
(https://link.getmailspring.com/link/cf1dfc14-e01b-46b3-9719-6dca72108...@getmailspring.com/0?redirect=https%3A%2F%2F3v4l.org%2FLHcmN=aW50ZXJuYWxzQGxpc3RzLnBocC5uZXQ%3D)
On Dec 1 2020, at 6:56 pm, Aimeos | Norbert Sendetzky  
wrote:
> Am 01.12.20 um 18:47 schrieb G. P. B.:
> >>> Or is_file could check for it, handle it gracefully, and be a safe
> >>> function to call without worrying about this undocumented edge case.
> >>
> > Apologize my email client sent by mistake:
> > But this has always generated a warning see:
> > https://3v4l.org/7E2mv
> >
> > So this is not new behaviour.
>
> A warning is OK but now an exception is now thrown so it's very
> different from versions before PHP 8.
>
> Furthermore, Christoph's code uses str_contains() which is only
> available in PHP 8 so it's not a good workaround if PHP 7 and 8 must be
> both supported.
>
> Personally, I would agree with Paul because the additional code that's
> necessary for the workaround complicates the user code base.
>
> Best,
>
> Norbert
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>



Re: [PHP-DEV] Thank you to JetBrains (PHP 8 Announcement page)

2020-11-27 Thread Benjamin Morel
On Fri, 27 Nov 2020 at 17:44, G. P. B.  wrote:

> PRs are always welcome on https://github.com/php/web-php :)
>
> PS: Please try to remember to bottom post and not top post.
>

Thanks for the pointer! Submitted as https://github.com/php/web-php/pull/364

And sorry for the top-post, I happen to forget it from time to time.

— Benjamin


Re: [PHP-DEV] Thank you to JetBrains (PHP 8 Announcement page)

2020-11-27 Thread Benjamin Morel
I really like this page as well! It will definitely help improve PHP's
reputation and adoption.

I'd like to suggest a couple improvements, though:

1/ Match expression:

The new match is similar to switch and has the following features:
> (...)
> *+ Match throws an UnhandledMatchError if no match is found*


2/ Nullsafe operator:

Instead of null check conditions, you can now use a chain of calls with the
> new nullsafe operator.
> *- When the evaluation of one element in the chain fails*, the execution
> of the entire chain aborts and the entire chain evaluates to null.
> *+ When one element in the chain evaluates to null*, the execution of the
> entire chain aborts and the entire chain evaluates to null.


IMO, "fails" could imply that an unknown property, or a property that
evaluates to a non-object is acceptable.

Sorry if these suggestions come a bit late, now that translations have
landed.

— Benjamin


On Fri, 27 Nov 2020 at 16:40, Sara Golemon  wrote:

> I've been receiving fantastic feedback on the PHP 8.0 Announcement landing
> page ( https://www.php.net/releases/8.0 ), and I just wanted to extend a
> big Thank You to all the folks at JetBrains for making this suggestion and
> putting forth the work on the initial four translations (en, pt_BR, de, and
> ru).  This has helped spread the excitement around this release, and I hope
> we continue the tradition next year!
>
> -Sara
>
> P.S. - It's especially encouraging that our community stepped up
> immediately to provide two more translations (fr and zh; plus I happen to
> know my wife is working on Spanish as I type this).
>


Re: [PHP-DEV] Why there is no StreamWrapper interface ?

2020-11-12 Thread Benjamin Morel
On Thu, 12 Nov 2020 at 19:28, Sara Golemon  wrote:

> Honestly, I kind of regard the state of PHP's filesystem libraries to be
> one big hot mess.  I'd really much rather redesign them from the ground up
> with some BC shims to avoid breaking the world, but I lack the drive to
> make that happen at the moment.
>
> -Sara
>

There have been some attempts (including mine) to design a better
abstraction on top of current PHP filesystem functions, which would be a
good start, but I think what's missing the most currently is a good API to
get inspiration from.
Is there a filesystem library in another language that is considered
state-of-the-art at the moment?

— Benjamin


Re: [PHP-DEV] Nullsafe

2020-11-03 Thread Benjamin Morel
On Tue, 3 Nov 2020 at 17:38, Eugene Sidelnyk  wrote:

> I am wondering why don't we use ordinary `->` operator with safe null
> handling?


Hi,

- changing the current behaviour of `->` would be a huge BC break
- and if we need another reason, there are many situations where you do
want to fail early if the left operand is null, so the current operator is
a good fit

— Benjamin


Re: [PHP-DEV] RFC: Support for multi-line arrow functions

2020-10-30 Thread Benjamin Morel
On Fri, 30 Oct 2020 at 19:07, Rowan Tommins  wrote:

> Just to be clear, the major gain here is not replacing the 10 characters
> "function()" with the 7 characters "fn() =>", it is eliminating the list
> of captured variables. So you would get equally clean code with a
> "capture all" syntax, such as:
>
>  return $connection->transactional(function() use(*) {
>
> or Sara's suggestion from earlier today:
>
>  return $connection->transactional(function() use($) {
>

Any of those would be a large improvement over the current situation I
agree.

That being said, for what it's worth, I've also proposed on the PR on GitHub
 an
alternative syntax for a closure that takes no parameters and inherits the
full scope:

$connection->transactional({
// ...
});

So yes, this would be a closure:

$a = {};

I'm not sure if this would be considered (additionally, not as a
replacement), but I thought it'd be worth mentioning, as it would offer an
elegant solution for methods whose body is pretty much only a call to a
method wrapping a closure.

— Benjamin


Re: [PHP-DEV] RFC: Support for multi-line arrow functions

2020-10-29 Thread Benjamin Morel
On Tue, 6 Oct 2020 at 14:09, G. P. B.  wrote:

> And once *again* short-closure don't *just* have the auto-import of the
> outer scope going for it.
> The other main features of the short closure are not applicable to a block
> syntax.
>  - the fact that there is an implicit return
>  - it is a single expression,
> **no* braces therefore it doesn't look like it creates a new scope.*
>

I'd like to come back to this. Actually there is a precedent in PHP where
braces don't create a new scope:

$a = 1;

{
$a++;
}

echo $a; // 2

I'm not sure why this syntax was allowed in the first place, but it is. So
I wouldn't be bothered if we create yet another case of block not creating
a new scope.

I'd like to emphasize the use case brought by Andreas Leathley:
transactional scope. I'm doing more and more of this these days, and I find
it very appealing:

$connection->transactional(function() {
// send raw SQL queries
// or create a scoped EntityManager
// etc.
});

This is, IMO, the only way to easily guarantee that any `return` will
commit the transaction, and any `throw` will roll it back. Otherwise, you
must remember to wrap your *whole* block with try {} and
catch/rollback/rethrow. That's a lot of clutter that you'll typically want
to avoid when you're repeating this in each and every method of every
service.

Now, the example above doesn't convey the purpose of the RFC on its own.
Let's put it into context, here is how one of my service methods looks like:

return $connection->transactional(function() use ($authorId,
$activityId, $parentId, $comment) {

... and this is not the largest one. Let's see how it would look like with
this proposal:

return $connection->transactional(fn() => {

This may not look like a big gain for you, but this would make all my
services look MUCH cleaner. And I'm not worried about scope leaking:
usually, the closure takes up most of my service method.

— Benjamin


Re: [PHP-DEV] List of attributes

2020-10-23 Thread Benjamin Morel
On Fri, 23 Oct 2020 at 19:08, Michael Voříšek - ČVUT FEL <
voris...@fel.cvut.cz> wrote:

> We can deprecate comments with "#" in 8.0 or 8.1
>
> ...
>
> Is there anything against excl. BC break of "#" comments? Who is for it?
>
>
I'm all for it, especially considering that it's trivial to fix old
codebases with automated tools with 100% confidence.
But I'm afraid it's too late to do this for 8.0, even though a major
release would have been the perfect time to deprecate such a feature.

— Benjamin


Re: [PHP-DEV] PHP 8 release announcement page on php.net

2020-10-19 Thread Benjamin Morel
I can handle the French one if you need someone.
Just send me the texts!

— Benjamin

On Mon, 19 Oct 2020 at 15:59, Sergey Panteleev 
wrote:

> Hi there!
>
> I'm also ready to help with Russian translation
>
> wbr,
> Sergey Panteleev
> On 19 Oct 2020, 16:54 +0300, Roman Pronskiy ,
> wrote:
> >
> > From a technical perspective, I assume it should be possible to reuse
> > php.net/manual/ mechanism for translations.
> >
> > As for the texts, the only way we can finish translations by November
> > 26 is if we get community help. Because JetBrains localization
> > resources will be overwhelmed during this period. Alexander and I can
> > do Russian. Do you think we can get help with other languages?
>


Re: [PHP-DEV] RFC: Support for multi-line arrow functions

2020-10-03 Thread Benjamin Morel
>
> If you want to make an RFC about it, it really needs a compelling "pros"
> section, because there aren't any, so far :-\


I don't agree. There is one pro, and not a small one IMO if you use
closures a lot: skip use().

Since arrow functions have been introduced, I've several times naturally
tried to open braces, only to remember that it's not supported.
I love fn() for the fact that it doesn't require the use() statement, and
would love to see it extended to more than a simple expression.

— Benjamin


Re: [PHP-DEV] Re: Attributes and constructor property promotion

2020-09-28 Thread Benjamin Morel
On Mon, 28 Sep 2020 at 15:17, Nicolas Grekas 
wrote:

> I assume the 80% case is properties, because attributes did not have
>> docblock annotations yet, that means this use-case isn't even possible at
>> the moment. Yet annotations on properties are widespread (Doctrine ORM,
>> symfony validator, ...).
>>
>
> I'm 100% with Benjamin here, this is what will be the most useful to me
> also.
>

To be clear, I don't have a strong opinion against yours, I'm just pointing
out the fact that even though it might be useful, it might also be
confusing and create yet another WTF moment in PHP for developers. Sure, it
might make more sense to apply to the property. Sure, so far annotations
weren't possible on parameters. But is that obvious to the average
developer writing the attribute? A few years down the road, DI containers
may have broad support for annotating parameters for injection. Will it
still be obvious then that an attribute on a promoted property applies to
the property only?

I do agree that applying the attribute to both the property and the
parameter will probably never be useful, though. So, throwing an exception
and forcing the de-sugaring feels like the most sensible thing to do for me
in this case!

— Benjamin


Re: [PHP-DEV] Re: Attributes and constructor property promotion

2020-09-28 Thread Benjamin Morel
  On Mon, 28 Sep 2020 at 13:56, Benjamin Eberlei 
wrote:


> imho, we should pick the 80% use-case and advise to desugar the code if
> other behavior is desired. For me the 80% case is that the attribute only
> applies to the property, not to the parameter.


+1 for the desugaring advice in this case, however as a matter of
consistency I'd rather have it either apply to both the property and the
parameter, or just throw an exception if used on promoted properties,
whatever the 80% use-case is (source?)

Kind regards,
— Benjamin


Re: [PHP-DEV] Attributes and strict types

2020-09-22 Thread Benjamin Morel
I'd expect it to obey the strict_types declaration of UseOfMyAttribute.php,
too. I see it as being where the attribute's constructor is "called", even
though the actual object instantiation happens somewhere else.

— Benjamin

On Tue, 22 Sep 2020 at 16:11, Larry Garfield  wrote:

> On Tue, Sep 22, 2020, at 7:58 AM, Nikita Popov wrote:
> > Hi internals,
> >
> > I would like to clarify how attributes are supposed to interact with
> > strict_types. Consider the following code, split up into three files to
> > make it clear that each one could have their own strict_types mode:
> >
> > MyAttribute.php
> >  > #[Attribute]
> > class MyAttribute {
> > public function __construct(string $a) {}
> > }
> >
> > UseOfMyAttribute.php
> >  > declare(strict_types=1);
> > #[MyAttribute(42)]
> > class Test {}
> >
> > AccessOfAttribute.php
> >  > var_dump((new
> > ReflectionClass(Test::class'))->getAttributes()[0]->newInstance());
> >
> > Currently, what happens is that this code will construct the attribute,
> > converting int 42 into string "42", even though UseOfMyAttribute.php has
> > strict_types=1.
> >
> > My intuitive expectation here would be that we should be following the
> > strict_types mode of wherever the attribute is being used (i.e.
> > UseOfMyAttribute.php, not MyAttribute.php or AccessOfAttribute.php).
> > Currently, we always assume strict_types=0.
> >
> > Is my expectation correct?
> >
> > Regards,
> > Nikita
>
> I could see an argument for either UseOfMyAttribute.php or
> AccessOfAttribute.php.  I think I would also favor UseOfMyAttribute.php,
> however, because if you get it wrong the place you have to change it is in
> that file, so it should obey the setting in that file.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Community vote on RFCs

2020-08-19 Thread Benjamin Morel
>
> You're asking for useless, no-effort feedback in the form of votes
> from people who have no actual involvement in the ongoing development
> or maintenance of the project, so that's what I gave you.


I'm surprised by these strong feelings. As a contributor and maintainer of
several open source projects, I'm always influenced by the number of thumbs
up/down feedback a message receives when reading discussions on GitHub,
whether they are from members/contributors of the project, or from
seemingly strangers. Of course, I'll often check *who *the feedback is
coming from, and this influences me as well.

I feel like this kind of feedback on the RFCs would be valuable to people
who have a right to vote, especially if there was a way to extract
specifically the feedback from open source project leads or heavy
contributors.

But you may disagree, of course.

- Benjamin


Re: [PHP-DEV] Community vote on RFCs

2020-08-19 Thread Benjamin Morel
Thank you for your feedback, Ben & Stanislav.

*Ben:*

It’s all fairly transparent, and if non-voting members want to provide
> input, they have various ways to do so (e.g., posting here, giving
> feedback to someone who is active here, etc.).


While this is true, I'm afraid the opportunities to provide "lightweight"
feedback are fairly limited. For the same reason I hate not being able to
just "+1" a message on @internals without having to reply and pollute the
thread with just a thumbs up, I feel like someone may just want to give
their opinion in a poll, without having to post a "I like XXX
syntax" message on @internals.

I think it would need to be clear that this is not a
> binding *vote*. Rather, it’s an informal *poll* to gauge
> support/interest in something. People who do have RFC voting privileges
> are not obligated to vote one way or another based on the results of
> the poll.


A *poll *reflects much better what I had in mind, indeed!

In the end, it may be best if an informal poll like this is conducted
> by a third-party who does not have RFC voting privileges (so that they
> could be considered neutral and unrelated to internals).


I don't have RFC voting privileges, so this condition would be met.


> There’s nothing stopping anyone from doing this right now. :-)


Actually there is: without a link to the poll in the RFC itself, the poll
would probably not get enough visibility to be useful.

*Stanislav:*

If
> somebody wants to voice an opinion, it's always welcome. But let's not
> pretend like people who actually maintain PHP core and everybody who
> ever used PHP or may be thinking about using it have equal weight here.


The whole idea would be to give people a straightforward way to voice their
opinion, without polluting @internals. As stated above, the wording would
be very clear that this is just a poll to help actual voters make an
informed decision, nothing more. If the poll gives a different result than
the RFC, the RFC obviously wins.

Please feel welcome to. However, I don't think this should have any
> official role in any PHP governance process, any more than any other
> poll on the internet might. That said, my opinion is hearing other
> opinions is rarely harmful and frequently useful, so why not.


Again, this would only be useful if linked to from the RFC. Hence I'd need
to get some kind of approval on the idea here before venturing into an
implementation.

- Benjamin


[PHP-DEV] Community vote on RFCs

2020-08-19 Thread Benjamin Morel
Hi internals,

The heated debate about attribute syntax made me think once again that it
would be valuable to get feedback in the form of votes from the community,
not just from core developers, on RFCs under discussion.

Understandably, the RFC voting process needs to be restricted to carefully
selected people, mostly core developers. But the fact is, this process is a
bit elitist, and fails to represent the community as a whole. A recent
thread  showed that even very active
contributors to OSS are unlikely to ever get a vote.

A project being nothing without its users, it would be nice to know whether
an important change will make them happy or not.

Therefore, I have in mind to develop (time permitting) an experimental
tool, external to the PHP wiki, that would replicate the voting options of
each RFC, but would allow everyone with a GitHub account to vote on the
same options as the original RFC. While the vote results would not directly
affect the wiki's vote results, I guess that this community feedback could
be taken into consideration by wiki voters and help them make an informed
decision.

To be useful, a link to the community voting site would need to be present
in each RFC, ideally some time before the actual voting starts on the wiki.

If popular enough, this tool could offer some analysis capabilities, such
as "what's the vote results from people having at least 100 commits to the
top 1000 packagist projects in the last year?" to help filter out the noise.

Thoughts?

Kind regards,
Benjamin


Re: [PHP-DEV] [VOTE] Shorter Attribute Syntax Change

2020-08-18 Thread Benjamin Morel
On Tue, 18 Aug 2020 at 08:49, Aleksander Machniak  wrote:

>
> I wonder why my suggestion (somewhere in this thread) didn't get any
> attention. Is it because the ship had sailed or it's a terrible idea?
>
> declare(
> SomeAttr,
> AnotherAttr("Hello world")
> )
> function someFunc() {
> }
>

This syntax has its benefits, but IMHO looks a bit clumsy for simple
annotations, and does not make it stand out as an annotation to my eyes:

declare(Inject)
class Foo {
}

But this may be just me.

— Benjamin


Re: [PHP-DEV] [VOTE] Shorter Attribute Syntax Change

2020-08-15 Thread Benjamin Morel
>
> I am for stopping the current voting too - because the results are very
> different vs. the previous voting, they are almost random and the
> discussion is still very hot which violates rule when voting can be
> started.


For what it's worth, I'm for resetting the voting, too, and restart it once
the discussion has settled a bit. The debate is still very heated, and
quite a lot of people seem to think they haven't been heard or haven't had
the time to contribute.

— Benjamin


Re: [PHP-DEV] [VOTE] Saner string to number comparison

2020-07-17 Thread Benjamin Morel
Thanks for this RFC, Nikita! This is definitely a step in the right direction, 
and I can only hope it will pass.

One question:

> (...) by using a number comparison only if the string is actually numeric. 
> Otherwise the number is converted into a string, and a string comparison is 
> performed.

Is there a reason to perform another comparison as a string, when the string is 
not numeric? I can’t think of a case where the string comparison would match.

- Benjamin

Re: [PHP-DEV] Re: [RFC] [VOTE] Locale-independent float to string cast

2020-05-07 Thread Benjamin Morel
Thank you Mate, this will be a very welcome change, that will naturally fix
bugs such as this one , and probably
others going unnoticed.

Benjamin

On Thu, 7 May 2020 at 14:02, Máté Kocsis  wrote:

> Hi Internals,
>
> I'm pleased to announce that the Locale-independent float to string cast
> RFC has been accepted with 41 votes in favour, and 1 vote against.
> According to the result of the secondary vote, the
> debug_locale_sensitive_float_casts ini setting won't be introduced.
>
> Cheers:
> Máté
>
> Máté Kocsis  ezt írta (időpont: 2020. ápr. 23.,
> Cs,
> 10:10):
>
> > Hi Internals,
> >
> > We have just opened the vote on the Locale-independent float to string
> > cast RFC. The voting will be open for two weeks, until 2020-05-07 12:00
> UTC.
> >
> > Link: https://wiki.php.net/rfc/locale_independent_float_to_string
> >
> > Cheers,
> > Máté
> >
> >
>


Re: [PHP-DEV] Moving json extension to core?

2020-04-29 Thread Benjamin Morel
>
> Looking at Ubuntu 20.04, they seem to
> have json built-in to the core package anyway. I'm not sure about other
> distros.


Fedora packages it separately as php-json.

I'm a big +1 on moving this extension to core. I've actually asked 2 weeks
ago if it could be disabled
,
because I want my classes to implement JsonSerializable, but this means
requiring ext-json and bumping the library version.

- Ben


Re: [PHP-DEV] [RFC][DISCUSSION] Change var_export() array syntax touse short hand arrays

2020-04-08 Thread Benjamin Morel
> VAR_EXPORT_NO_INDEX

Note that I wouldn't consider a BC break to change var_export()'s behaviour
to always discard indexes when they're numeric, I'm not sure this should
even be an option!

- Ben


Re: [PHP-DEV] [RFC][DISCUSSION] Change var_export() array syntax to use short hand arrays

2020-03-30 Thread Benjamin Morel
>
> If "they" don't care about syntax, then why do you?


Sorry I was unclear. I was reacting to the argument about broken tests in
php-src.
I meant: they don't have *expectations* about the syntax, but they'll most
likely want to be able to read it.

— Benjamin


Re: [PHP-DEV] [RFC][DISCUSSION] Change var_export() array syntax to use short hand arrays

2020-03-30 Thread Benjamin Morel
>
> "Then why not use brick/varexporter?"


As much as I'm pleased that people use this library, I consider it a shim,
waiting for PHP to ultimately provide the same functionality.
See the (object) cast for stdClass, that was supported by varexporter but
was later added to var_export().
I don't see a reason not to follow with the short array syntax; the only
expectation of people using var_export(), AFAIK, is to get valid PHP code;
they don't care about the syntax, which will be retro-compatible as far as
PHP 5.4, if that's even a consideration when PHP 8.0 is released.

— Benjamin


Re: [PHP-DEV] [RFC][DISCUSSION] Change var_export() array syntax to use short hand arrays

2020-03-29 Thread Benjamin Morel
+1 for this.

This is the syntax I'm using in brick/varexporter
, and supporting it natively in
var_export() makes sense.

— Benjamin


Re: [PHP-DEV] Class cast

2020-03-25 Thread Benjamin Morel
>
> Currently PHP supports generic castings like (string), (int), ... maybe is
> time to allow class castings like (ToClass) $fromObject?


I've proposed something similar a year ago:
https://externals.io/message/105332

My intention wasn't to create an object from a scalar, nor was it to limit
to a class' methods & properties (hardly possible in PHP), but to ensure
that the value is an instance of the given class/interface, or throw an
exception.
My proposal wasn't so well received, though.

— Ben


Re: [PHP-DEV] Proposal for a new basic function: str_contains

2020-02-17 Thread Benjamin Morel
>
> Thanks for the karma! An RFC has been created:
> https://wiki.php.net/rfc/str_contains



Something that's missing from the RFC is the behaviour when $needle is an
empty string:

str_contains('abc', '');
str_contains('', '');

Will these always return false?

— Benjamin


Re: [PHP-DEV] RFC: Server-Side Request and Response Objects (v2)

2020-02-14 Thread Benjamin Morel
>
> What about $query and $body? That would be closer to the terminology
> used in HTTP RFCs.



The problem is that $body is typically used to get the raw message body as
a string or stream.
I was thinking more something along the lines of $bodyParams, which is more
verbose but leaves no ambiguity: *$queryParams* and *$bodyParams*.

— Benjamin


Re: [PHP-DEV] RFC: Server-Side Request and Response Objects (v2)

2020-02-14 Thread Benjamin Morel
>
> Having said that, we are willing to revisit that naming decision if
> there's support for doing so. Perhaps:
> - rename $get to $query, populating it from `$globals['_GET']`, on the
> basis stated above
> - rename $post to $input, populating it from `$globals['_POST']`, on the
> basis that it typically relates to the parsed form of php://input
> Your (and/or anyone else's) thoughts on that?



Symfony uses $request->query and $request->request for $_GET and $_POST,
respectively.
I like $request->query for query params, but always found $request->request
for body parameters confusing. I like $request->input a bit better,
although I'd be interested to hear more ideas on this one.

— Benjamin


On Fri, 14 Feb 2020 at 16:47, Paul M. Jones  wrote:

> Hi Côme & Niklas,
>
> > On Feb 13, 2020, at 04:52, Côme Chilliet <
> come.chill...@fusiondirectory.org> wrote:
> >
> > Le mercredi 12 février 2020, 19:20:56 CET Niklas Keller a écrit :
> >
> >> Naming
> >>
> >> I think we shouldn't take over the naming of the super globals, e.g.
> >> $_GET really contains the query parameters and has nothing to do with
> >> GET or POST, so $request->getQueryParameter(...) would be a better
> >> name.
> >
> > I think this remark is really on point.
> > GET and POST are HTTP methods and not ways of passing data. You can have
> query parameters on any request, and you can have POST data with a lot of
> other HTTP methods, as is commonly used in REST APIs.
>
> Your comments on naming are well-made.
>
> While working on the implementation, we tried out $query instead of $get,
> on exactly the premise that you state: i.e., that `$_GET` holds the query
> parameters, and has nothing to do with the GET method. But in the end, we
> settled on mapping more directly from `$_GET` => `$get`, and `$_POST =>
> $post`.
>
> Having said that, we are willing to revisit that naming decision if
> there's support for doing so. Perhaps:
>
> - rename $get to $query, populating it from `$globals['_GET']`, on the
> basis stated above
> - rename $post to $input, populating it from `$globals['_POST']`, on the
> basis that it typically relates to the parsed form of php://input
>
> Your (and/or anyone else's) thoughts on that?
>
>
> --
> Paul M. Jones
> pmjo...@pmjones.io
> http://paul-m-jones.com
>
> Modernizing Legacy Applications in PHP
> https://leanpub.com/mlaphp
>
> Solving the N+1 Problem in PHP
> https://leanpub.com/sn1php
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Moving the documentation to git

2020-02-03 Thread Benjamin Morel
>
> So the main question is now, how the PHP-Project wants to go on with
> moving the documentation from SVN to git? Is there any interest in
> continuing this project?


Yes please. I would contribute a thousand times more if I could just make
PRs on GitHub.
Right now I'm being put off by the documentation editor.

— Benjamin


Re: [PHP-DEV] Operator overloading for userspace objects

2020-01-31 Thread Benjamin Morel
I like this whole operator overloading thing. I would probably use it in
brick/math  and brick/money
 to replace verbose `->plus()`,
`->multipliedBy()` etc. calls.

> Can you only compare 2 of the same type?  What about subclasses?  Can
that differ if a subclass overrides that method?  What happens to
commutativity then?  Can you compare based on an interface?

I think that this should behave exactly the same as if you replaced `$a +
$b` with `$a->__add($b)` in your code. Nothing more, nothing less. The
result will depend on whether you type-hinted your magic method or not.

> These operators only make sense on value objects, not service objects,
and value objects should be immutable.

Indeed, we would need to make it clear that the operation must not modify
the value of the current object, that should be effectively treated as
immutable.
Because it will probably be hard for the engine to enforce this, what about
using the same convention I use in my libraries, i.e. `plus()` instead of
`add()`, `dividedBy()` instead of `divide()`, etc.?

This would translate to magic methods such as:

__plus()
__minus()
__multipliedBy()
__dividedBy()

Benjamin


Re: [PHP-DEV] How to debug a segmentation fault?

2020-01-30 Thread Benjamin Morel
>
> Infinite recursion leading to a segfault is **a known bug with no plans to
> be fixed that I know of,** which I've encountered many times.


That's unfortunate; as I said in the bug report, it's so easy to trigger
and so easy to miss when reviewing the code! And the process crashing
instead of reporting an error is really a pity.
An explicit error message would be nice, but as I understand this would
require setting a hard limit on the call stack depth, which may bring other
issues.

Thank you,
— Benjamin

On Thu, 30 Jan 2020 at 03:59, tyson andre  wrote:

> > Sorry, I didn't notice that https://bugs.php.net/bug.php?id=79194 was
> already [solved and] closed with a similar answer.
>
> In addition to phpspy, a tool I forgot to mention was Phan. (
> https://github.com/phan/phan)
>
> `phan --redundant-condition-detection` will enable many of Phan's checks,
> including code that looks like a function or method calling itself
> unconditionally, or with the same args.
> I got the idea for adding a check for PhanInfiniteRecursion
> (and PhanPossiblyInfiniteRecursionSameParams) after investigating a similar
> segfault over a year ago ago
> (and considering most of those solutions),
> to detect that type of bug before it ran.
>
> https://github.com/phan/phan/blob/master/internal/Issue-Types-Caught-by-Phan.md#phaninfiniterecursion
> has an example of what it detects


Re: [PHP-DEV] How to debug a segmentation fault?

2020-01-29 Thread Benjamin Morel
>
> I would add, since you're using PHP-FPM, that the pool configuration needs
> to have:
> process.dumpable = 1


Thank you! I could not generate a core dump before adding this
configuration option!
The generating a gdb backtrace
<https://bugs.php.net/bugs-generating-backtrace.php> page looks a big
outdated, it would be nice if someone could update it will all the helpful
info received in this thread.

I'm not sure if I could gather helpful enough info about the issue, but
anyway I filed a bug here:
https://bugs.php.net/bug.php?id=79194

Thank you,
Benjamin

On Wed, 29 Jan 2020 at 18:19, Bishop Bettini  wrote:

> On Tue, Jan 28, 2020 at 11:28 AM Benjamin Morel 
> wrote:
>
>> I'm encountering a SIGSEGV in PHP-FPM on PHP 7.4.2 in a Symfony app. The
>> bug seems to happen during the rendering of a Twig template; this makes it
>> hard for me to pinpoint the code that triggers the segfault.
>>
>> Could you please tell me what the procedure to collect information is, so
>> that I can file a useful bug report?
>>
>
> Great advice so far. I would add, since you're using PHP-FPM, that the
> pool configuration needs to have:
>
> process.dumpable = 1
>
> to get core dumps out of workers. Without this you might not get core
> dumps, even when you have other core dump settings configured (ulimit -c
> unlimited, chmod +r phpfpm, etc.).
>


[PHP-DEV] How to debug a segmentation fault?

2020-01-28 Thread Benjamin Morel
Hi internals,

I'm encountering a SIGSEGV in PHP-FPM on PHP 7.4.2 in a Symfony app. The
bug seems to happen during the rendering of a Twig template; this makes it
hard for me to pinpoint the code that triggers the segfault.

Could you please tell me what the procedure to collect information is, so
that I can file a useful bug report?

Thank you,
— Benjamin


Re: [PHP-DEV] The future of SQLite3 and PDO/SQLite extensions

2020-01-27 Thread Benjamin Morel
>
> I think that PDO_SQLite should get the same features as the SQLite3
> extension, and the SQLite3 extension should be deprecated and
> eventually removed and replaced by a userland library that would wrap
> around the PDO_SQLite API.


Hi BohwaZ,

Having only PDO_SQLite sounds good to me. Currently, it cannot be used to
load SQLite extensions , so this is
one of the reasons one may have to stick with SQLite3.
If the PDO_SQLite features come on par with those of SQLite3, I personally
see no reason not to ditch SQLite3 eventually.

— Benjamin


Re: [PHP-DEV] Typed array properties V2

2020-01-21 Thread Benjamin Morel
>
> What if we left the array type alone, and instead focussed on "list"
> type and "dict", "dict" types?



> That would allow a clear break from previous behaviour, and would allow you
> to introduce other changes (e.g. removing string -> int coercion for
> numeric string keys).



Can't agree more.

— Benjamin


[PHP-DEV] Union types | true pseudo-type

2020-01-20 Thread Benjamin Morel
Hi internals,

I'd like to bring back the topic of supporting "true" as a type in PHP 8
union types.
Now that the RFC  has been
successfully voted, I'd like to revive the discussion about adding the
"true" pseudo-type in addition to "false".

In addition to my Packagist survey
, I'd like to point out that I
just came across a native method in the SSH2 extension, that does use true
as a type:

https://www.php.net/manual/en/function.ssh2-auth-none.php


Returns TRUE if the server does accept "none" as an authentication method,
> or an array of accepted authentication methods on failure.



Of course, you could type-hint it array|bool, but the same could be said
for |false.

Thoughts?

— Benjamin


[PHP-DEV] WeakMap vs PECL WeakMap

2020-01-20 Thread Benjamin Morel
Hi Internals,

A year ago, when WeakRef was being proposed, some objections
 related to the PECL Weakref
package  had lead the RFC
author, Joe Watkins, to rename WeakRef to WeakReference to avoid conflicts.

However, the latest addition from Nikita Popov, WeakMap
, did not take the same argument into
account, therefore conflicting with PECL WeakMap
.

*First of all, how will this be handled in the docs?*

Now that we have a conflict on WeakMap anyway, and now that the PECL
package has been deprecated, and provided that the conflict can be
gracefully handled in the docs, *is there anything that prevents
WeakReference from being called WeakRef?*

Could we have both names in PHP 8, like WeakReference being an alias for
WeakRef?

Thank you,
Benjamin


Re: [PHP-DEV] Re: VCS Account Request: nicolasgrekas

2020-01-15 Thread Benjamin Morel
I've been actually surprised by the rejection myself, especially
considering that @ocramius, whose profile seems similar to Nicolas',
already has a seat.
Don't get me wrong, I have a lot of respect for @ocramius and all of his
work on PHP open-source projects, but he doesn't seem to have contributed a
lot to the PHP source code itself neither:

https://github.com/php/php-src/commits?author=ocramius

So I always thought, well of course he has a vote as an influent member of
the userland library developer community, and this is healthy. And there
should be more of them.
But then why not give a vote to Nicolas as well, given his huge
contributions to userland PHP projects, and his occasional contributions to
PHP itself?

Something does not seem right here.

— Benjamin


Re: [PHP-DEV] [RFC] Static return type

2020-01-08 Thread Benjamin Morel
>
> I would like to propose the following RFC, which allows using "static" as a
> return type:
> https://wiki.php.net/rfc/static_return_type



Big +1 from me as well. I actually asked why this wasn't supported back in
2015:

static return type in PHP 7 interfaces


— Benjamin


Re: [PHP-DEV] Support for Async / Await

2019-12-23 Thread Benjamin Morel
>
> Does this actually fit in with php's execution model of each request
> being a separate thread / process?



I can see this being useful, when AJAX-querying an endpoint that has to do,
in turn, 2 or more API calls or other async jobs to build its response.
(although async HTTP requests are already possible with curl).

— Benjamin


Re: [PHP-DEV] Let's allow eval() to be turned off in PHP 8

2019-11-26 Thread Benjamin Morel
>
> One interesting thing with item #1 is that it allows for remote arbitrary
> code execution even if no include-able path on a server is writable. This
> comes into play if there's a supply chain attack on your app. Say, an
> infected update on a CMS plugin. Get an eval() of a file_get_contents() of
> a URL into the code and...well, you get code execution that (if you're
> lucky) only leaves a trace in logs. If you have to write a file somewhere
> first, then include it, you've got a bit more of a footprint.



You don't have to hit disk, or have any writable path. You can just create
a stream wrapper 
that stores the "files" in memory, and include them as you would include a
regular file.


Can you work around these restrictions? Yep, but it takes a bit more effort
> than the current setup. It doesn't make a server secure by any stretch, but
> it reduces its attack surface slightly, and reduces the universe of
> malicious code that won't error out, forcing malefactors to work just a bit
> harder.



Disabling eval() really doesn't reduce the attack surface at all, if you
ask me. Malefactors will quickly & easily adapt their tools, that script
kiddies will use as before.


— Benjamin


Re: [PHP-DEV] Let's allow eval() to be turned off in PHP 8

2019-11-26 Thread Benjamin Morel
Hi Ian,

IMO, eval() is secure, as long as:

- you’re not using it, or
- you’re using it properly

I’d say that as soon as your server has been compromised, eval() is the last of 
your worries, as pretty much anything becomes possible, including writing PHP 
code to a file and including/executing it. So I feel like disabling eval() will 
just make « hackers » have a good laugh.

Regarding (arguably) legitimate use cases that would suffer from eval() being 
disabled, is a Schema.org parser library I wrote, that dynamically creates 
objects that implement arbitrary interfaces:

https://github.com/brick/schema/blob/master/src/ObjectFactory.php

IMHO, disabling eval() would not increase the security of PHP, and could be 
annoying for libraries relying (sparingly) on it, for lack of anything better.

Best,
Benjamin

> Le 26 nov. 2019 à 16:52, Ian Littman  a écrit :
> 
> Hi all,
> 
> Let's just say that eval() and create_function() are the cornerstone of
> PHP-based exploit toolkits. Yes, if the hackers get in there are other
> problems with your codebase, but as a defense in depth measure most
> applications need neither create_function() nor the eval() language
> construct, so they might as well be disabled.
> 
> create_function() is easy enough to drop with a didabled_functions ini
> directive, and is going away "no later than PHP 8.0", per its deprecation
> notice as of 7.2. eval() on the other hand can't be disabled that way, as
> it's not actually a function. So this seems like an excellent candidate for
> another ini setting, as from a security standpoint you *want* this change
> to be global. Yes, if every shared host turned this on by default, old code
> would break. But I Suhosin allows doing this anyway (
> https://stackoverflow.com/questions/25037015/suhosin-and-disable-eval) so
> it's not like the option hasn't been available...though it's been over four
> years since we've had a stable release of Suhosin.
> 
> Similar to disable_functions, if the ini setting turning off eval() got
> set, you shouldn't be able to override it via ini_set() in code. We can use
> a similar warning to the display_disabled_function one here.
> 
> One alternative to adding an entirely new INI setting would be to allow
> disabled_functions to work on eval. That means that somewhere in the INI
> parsing/stubbing/warning process (and maybe all three places) will get a
> bit more complex, but that would have the benefit of not having to explain
> to anyone editing the ini file that eval() is a language construct rather
> than a function and thus can't be disabled the normal way (I was just
> apprised of this mistake last today).
> 
> From taking a quick look at Suhosin code, the way they're handling this may
> be somewhat informative for creating a patch directly to core, but as a
> bolt-on it looks like they can't be as efficient, so any patch to core
> would be inspired by, rather than a copy of, how that extension's
> eval-handling is built.
> 
> I feel strongly enough about this to help with the text side of the RFC,
> and maybe even dive into php-src to assist with a patch, though I have
> neither karma for posting the former nor enough C acumen to do the latter
> all by myself. But I want to make sure I won't get immediately shot down if
> I try going down that road...and if other folks like the idea, I could use
> some help here putting it together.
> 
> What do y'all think about getting this into PHP 8?
> 
> Thanks in advance,
> 
> Ian Littman


Re: [PHP-DEV] [RFC] Add WeakMap

2019-11-05 Thread Benjamin Morel
Hi Nikita,

After reading the RFC, I have no comments to make, but I just want to thank
you for working on this. I regretted a lot that this wasn't implemented
together with WeakReference in PHP 7.4 ,
as the use cases for WeakReference vs WeakMap are really narrow.

Cheers,
Benjamin

On Tue, 5 Nov 2019 at 10:24, Nikita Popov  wrote:

> Hi internals,
>
> This is a follow up to the addition of WeakReference in PHP 7.4.
> WeakReference is an important primitive, but what people usually really
> need are weak maps, which can't be implemented on top of WeakReference (at
> least, not as exposed in PHP).
>
> This RFC proposes to add a native WeakMap type for PHP 8:
> https://wiki.php.net/rfc/weak_maps
>
> Regards,
> Nikita
>


Re: [PHP-DEV] Optional pre-compiler for PHP8?

2019-10-28 Thread Benjamin Morel
>
> This would break as soon as we have two versions of a class, and a
> runtime choice which of them to use.
> (see also Mark Randall's comment)



That's why I'm suggesting to only make these optimizations when preloading
is in use, which means that you know
ahead of time the class definitions, and you cannot have 2 runtime
definitions of a given class.

No preloading = no optimizations.
Full preloading (whole codebase) = maximum optimizations.
Partial preloading = the compiler should still be able to optimize *some *of
the code involving only the preloaded classes.

We already have, since PHP 7.4, a mechanism to know static class
definitions on startup, so why not build further optimizations on top of it?

⁠— Benjamin


Re: [PHP-DEV] Optional pre-compiler for PHP8?

2019-10-27 Thread Benjamin Morel
>
> > So we'd probably need some built-in definition of a "package", which
> could be analysed and compiled as one unit, and didn't rely on any run-time
> loading.
> That idea of a "package" came up during a debate on this list at least
> once, a few months ago, and I think it makes a lot of sense. And what I
> proposed effectively implies that namespaces would be treated like packages
> from the perspective of the compiler.



Putting aside the idea of distributing pre-compiled PHP scripts, if we're
only debating the precompilation as, notably, a means to reduce the cost of
type checks, I wouldn't mind if the precompilation occurred *only if
preloading is in use*, i.e if most class definitions are known on server
startup, which is when the compilation / optimization passes could occur.
No preloading = no such optimizations, I could personally live with that.

No need for a package definition, IMO.

— Benjamin

On Mon, 28 Oct 2019 at 00:56, Mike Schinkel  wrote:

> > On Oct 27, 2019, at 7:04 PM, Rowan Tommins 
> wrote:
>
> Thank you for your comments.
>
> > I chose the phrase "static analysis tool" deliberately, because I wanted
> to think about the minimum requirements for such a tool, rather than its
> long-term possibilities.
>
> Your points are all well-considered.
>
> To be clear, I wasn't stating the idea as a alternative to your idea, I
> was only stating that your comments inspired me to have the idea of a
> pre-compiler.
>
> IOW, I saw no reason both could not be done, one sooner and the other
> later.
>
> > However, combining those usefully may not be that easy.
>
> Also for clarity, I was not assuming existing OpCache would be 100%
> unmodified, I was talking about benefits that a pre-compiler could have and
> was less focused on ensuring it could slot into an existing OpCache
> implementation as-is.
>
> IOW, if it is worth doing it might be worth extending how the OpCache
> works.
>
> > So we'd probably need some built-in definition of a "package", which
> could be analysed and compiled as one unit, and didn't rely on any run-time
> loading.
>
> That idea of a "package" came up during a debate on this list at least
> once, a few months ago, and I think it makes a lot of sense. And what I
> proposed effectively implies that namespaces would be treated like packages
> from the perspective of the compiler.
>
> But then again a new package concept might be needed in addition to
> namespaces, I am not certain either way.
>
> > Unlike P++, Editions, or Strict Mode, this would undeniably define that
> the deprecated features were "the wrong way".
>
> I am not sure I cam agree that it would define them as the "wrong way."
>
> The way I would see it is there would be a "strict way" and an "unstrict
> way."  If you prefer the simplicity of low strictness and do not need
> more/better performance or the benefits of type-safety that are needed for
> building large applications, then the "right way" would still be the
> "unstrict way."
>
> And the non-strict features would not be "deprecated" per-se, they would
> instead be disallowed for the strict (compiled) way, but still allowed for
> the unstrict (interpreted) way.
>
> > If the engine had to support the feature anyway,
>
> I think we are talking two engines; one for compiling and another for
> interpreting.  They could probably share a lot of code, but I would think
> it would still need to be two different engines.
>
> > I'm not sure what the advantage would be of tying it to "compiled vs
> non-compiled", rather than opting in via a declare() statement or package
> config.
>
> The advantage would be two-fold:
>
> 1. Backward compatibility
>
> 2. Allowing PHP to continue to meet the needs of new/less-skilled
> programmers and/or people who want a more productive language for smaller
> projects that do not need or want all the enterprisey type-safe features.
>
> Frankly it is this advantage which is the primary reason I though to send
> a message to the list. The chance to have the benefit of strictness and
> high performance for more advanced PHP developers while still having full
> BC for existing code and for beginner developers seemed highly compelling
> to me.
>
> -Mike
>
>


Re: [PHP-DEV] Re: [RFC] Union Types v2

2019-10-26 Thread Benjamin Morel
>
> As they are runtime checks, would an ini setting where they can be
> completely disabled be feasible? So during development and in production
> when the performance decrease doesn't matter, I can have the full runtime
> type checking. But when absolutely needed, the checking can be disabled.



Note that I would personally never disable these checks in production, as
they may prevent potential bugs down the road, that would not have
necessarily been caught in dev.
I would rather expect PHP to bring down the cost of these checks in
production to a negligible level, as mentioned in my previous message
(static analysis and JIT).

— Benjamin

On Fri, 25 Oct 2019 at 10:09, Peter Bowyer 
wrote:

> On Thu, 24 Oct 2019 at 13:47, Rowan Tommins 
> wrote:
>
> > I think this performance impact is a real concern; PHP is the only
> language
> > I know of which implements type checks entirely at run-time in production
> > code, and we should ask ourselves if that's definitely the right
> approach.
> >
>
> As they are runtime checks, would an ini setting where they can be
> completely disabled be feasible? So during development and in production
> when the performance decrease doesn't matter, I can have the full runtime
> type checking. But when absolutely needed, the checking can be disabled.
>
> Peter
>


Re: [PHP-DEV] Re: [RFC] Union Types v2

2019-10-26 Thread Benjamin Morel
>
> I think this performance impact is a real concern; PHP is the only language
> I know of which implements type checks entirely at run-time in production
> code, and we should ask ourselves if that's definitely the right approach.


Would it be possible, at least in principle, to build a static analysis
> tool which could prove that certain type checks would never fail, and prime
> OpCache with code that leaves them out? As I understand it, this is how
> Dart works: the compiler only emits run-time checks for assertions it can't
> prove true by static analysis.



I was wondering the same thing, especially in the light of preloading,
where a lot of class/function definitions are known on startup.

For example, doing:

  function x(): int {}
  function y(int $foo) {}
  y(x());

Should definitely not redundantly check the type of the y() parameter, if
possible.

Also, in the case of JIT, shouldn't type hints actually *improve*
performance?

— Benjamin


On Thu, 24 Oct 2019 at 14:47, Rowan Tommins  wrote:

> Hi Dmitry,
>
> On Wed, 23 Oct 2019 at 16:43, Dmitry Stogov  wrote:
>
> > Actually, I think PHP already took wrong direction implementing "typed
> > references" and "type variance".
> > Introducing more "typing", we suggest using it, but this "typing" comes
> > with a huge cost of run-time checks.
> > From 10% (scalar type hint of argument) to 3 times (typed reference
> > assignment) performance degradation.
> > Anyone may rerun my benchmarks
> > https://gist.github.com/dstogov/fb32023e8dd55e58312ae0e5029556a9
> >
>
>
> I think this performance impact is a real concern; PHP is the only language
> I know of which implements type checks entirely at run-time in production
> code, and we should ask ourselves if that's definitely the right approach.
>
> Would it be possible, at least in principle, to build a static analysis
> tool which could prove that certain type checks would never fail, and prime
> OpCache with code that leaves them out? As I understand it, this is how
> Dart works: the compiler only emits run-time checks for assertions it can't
> prove true by static analysis.
>
> The simpler idea I had in this area was caching what type checks a value
> had passed, either on each zval or perhaps just at the class level, so that
> checking the same type again would be much faster, even if it was a complex
> union with multiple interfaces.
>
> Regards,
> --
> Rowan Tommins
> [IMSoP]
>


Re: [PHP-DEV] Reclassifying some PHP functions warning as exceptions

2019-10-22 Thread Benjamin Morel
@Mike,


> Then about a year ago I started using Go, and Go's approach to error
> handling just clicked for me. Go's philosophy is to handle the error as
> soon as you one is aware of it and to only ever handle it once.  Since I
> have been using that strategy I have become very happy with my error
> handling, and I now (attempt) to use the same strategy in my PHP code.
> So what I am hoping for is that PHP recognizes there are two strategies
> for error handling — 1. Throwing exceptions vs. 2. Returning error values —
> and that PHP 8.0 and behind will respect programmers and allow them to
> embrace the strategy they feel is best for their use-case.



I do see some value in the way Go handles errors (i.e. forcing you to deal
with them), especially the *expected* ones; the issue, if I'm not mistaken,
is how you deal with *unexpected* errors. AFAICS, this forces you to either
return it to the caller (which may not expect this error), or wrap it in a
more specific error that's part of your function's contract, which is
pretty much what you do with exception chaining. I don't have a hands-on
experience with Go, though, so I may have missed something. Please do
correct me if/where needed.


@Rowan,


You've backed that up with exactly one example function, and immediately
> concede a case where you might want a non-exception flow. Here are a
> handful more examples off the top of my head:
> * Attempt to atomically lock and open file, returning either a file
> handle or a "could not lock" status.
> * Attempt to read from a file, terminate loop when the file handle
> reaches EOF.
> * Attempt to delete file, ignore if it doesn't exist.
> All of these are candidates for returning false, or an error code, or an
> object in a particular status. They could be handled with exceptions,
> but that would force common patterns to use exceptions for flow control,
> which is generally seen as a "bad smell".



I used this one function as an example, but I'm happy to apply my point of
view to other examples if you wish. I'll take yours above, in reverse order:

*-  Attempt to delete file, ignore if it doesn't exist:*

unlink($file): bool; // true if the file was deleted, false if it didn't
exist; exception on other errors

As I see it, the only safe-to-ignore error is "the file does not exist"
(non-exceptional error), as the outcome is the same whatever the return
value: the file does not exist (anymore).
Any other error should, IMO, be treated as exceptional and throw.

*- Attempt to read from a file, terminate loop when the file handle reaches
EOF:*

I think the current API is already quite good at that, it just needs a bit
of polish in the way it handles errors:

while (! feof($fp)) $block = fread($fp, 4096);

feof($fp): bool; // true if EOF, false if not; exception on error
fread($fp): string; // the data, empty string if EOF (non-exceptional);
exception on error

I don't see much value in doing something like:

for (;;) {
$result = fread($fp, 4096);
if ($result->isEOF) break;
if ($result->error) {
// ...
}

$block  = $result->data;
}

*- Attempt to atomically lock and open file, returning either a file handle
or a "could not lock" status:*

fopen_and_lock($fp); // true if lock was acquired, false if not; exception
on error

This one is trickier, as the outcome is roughly the same (the file was
open) but maybe the lock failed to acquire. I can't say if I would return
bool, or void and an exception on failure-to-acquire.


Don't get me wrong, I respect your points of view, they are perfectly
valid, and as such I'm not trying to push exceptions over anything else;
but I don't personally see them as bad at all, they're actually quite
convenient if used properly. I do see some value in returning errors, too,
but with the strong caveat expressed below, that may severely affect
inexperienced, or, should I say it, lazy developers. I like the exception
model, breaking the program flow by default if unhandled. This makes an app
much more reliable *by default* IMHO.

Therefore I do like the original proposal, even if I can hardly imagine it
overcome the usual resistance here.
This proposal would be as good under the form of a new API though, but in
this case the naming should be changed to clearly differentiate both APIs.

I wish you luck, @David, anyway.

— Benjamin



On Mon, 21 Oct 2019 at 23:59, Rowan Tommins  wrote:

> On 21/10/2019 21:38, Benjamin Morel wrote:
> > Sure, you can do without exceptions. I think what you're suggesting is
> > similar to Go's error handling. But PHP at some point decided in
> > favour of exceptions, so it would be logical to pursue in that direction.
>
>
> I didn't say "do without exceptions", I said "use exceptions when
> they're the right tool, and other tools at other times".
>
>
> > I would cl

  1   2   3   >