Re: [PHP-DEV] What is the prevailing sentiment about extract() and compact() ?

2023-11-29 Thread David Gebler
On Wed, Nov 29, 2023 at 7:19 AM Stephen Reay 
wrote:

> So no, I don't think compact() should be deprecated, what I think *should*
> happen, is to promote the current warning on undefined variables, to an
> error, as per https://wiki.php.net/rfc/undefined_variable_error_promotion.
> Whether this is a foregone conclusion or not, I don't know because that RFC
> doesn't mention compact() specifically.
>
>
I remember fixing a bug in compact where passing parameters which were not
array or string were silently accepted - something I discovered when I was
tracking down a bug in my code once and it turned out I'd accidentally done
compact($x) instead of compact('x') - and that now gives a warning,
consistent with the warning when variable names given are undefined.

I don't want to see either compact or extract deprecated because I do use
both (as do countless open source systems) and I don't think there is a
reasonable justification for deprecating them. The behaviour of these
functions is understood by static analysis tools, the alternatives are more
verbose and more prone to developer error / mistakes from typos. I do agree
with upping the error level in compact() from E_WARNING to E_ERROR and
upping the warning on bad parameter types to a TypeError (which is what I'd
originally pushed for), but I think these things should be a change to
compact specifically, separate from any other RFC.

-Dave


Re: [PHP-DEV] RFC Proposal - static modifier for classes

2023-11-21 Thread David Gebler
I wouldn't support this, personally. I'm not a voter but I mean just in
terms of gauging community feel about the proposal, without unnecessarily
repeating what's already been said I just want to register that I'm in
agreement with Larry and Kamil's comments.

What static classes would achieve goes against the design principles of
what a class is and what it's for. Others have noted we already have an
adequate namespacing system and via Composer which is a de facto standard
in almost all PHP projects today, a means to autoload namespaced functions.

But more than that, I think for me - look, I get a lot of language features
which are sincerely useful can be argued to be just convenient syntax sugar
for things you could technically already do another way. But when I
consider features like readonly properties, constructor promotion and
readonly classes, I think the functional change goes beyond just syntax
sugar. You're getting an enormous saving versus say, trying to make a class
with all properties readonly in PHP 7.4. It's not just a little bit of
boilerplate trimmed down, it's you now have to write one line of code
instead of fifty.

So even if I supported the idea of static classes in principle, I'd still
be looking at it and thinking really the only convenience, the only syntax
sugar here is that you now have to type the word static N-1 fewer times
where N is the number of properties and functions in your class. This is
not a huge benefit or saving to me. While I wouldn't encourage anyone to
design their code this way, for the same reasons Larry has articulated, if
you want to design your code this way you already can at basically the same
cost of your time and effort and same cost to the PHP engine.

I think there'd need to be some persuasively more substantial gain for
either the developer or the execution of a script for this proposal to be
worth anything.

Thanks.

-David


Re: [PHP-DEV] Array functions with strict comparison

2023-11-13 Thread David Gebler
On Sun, Nov 12, 2023 at 8:20 PM Andreas Hennings 
wrote:

> So to me, this alone is an argument to implement this natively.
> The other argument is that it is kind of sad how the current functions
> don't behave as one would expect.


I'd expect there to be a larger and proportionately increasing performance
difference between array_diff versus array_udiff with callback or a
userland array_diff_strict function the larger the datasets you feed in.
But I'm not sure how common either the use case of diffing arrays of 25,000
or 250,000 elements might be, or needing this comparison to be strict
equality. I suspect the use case where both these conditions apply is very
rare.

But if you want to create an RFC, please go for it. You could add an extra
parameter to these functions after the input arrays, which was a flag for
strict comparison. Whether such a thing with a default value of non-strict
(so not BC breaking) would be considered preferable to new global
functions, I'm not sure. I'd probably go with new functions but maybe
someone else will weigh in with their thoughts.


Re: [PHP-DEV] Array functions with strict comparison

2023-11-11 Thread David Gebler
On Sat, Nov 11, 2023 at 6:05 PM Andreas Hennings 
wrote:

> Hello internals,
> I noticed that array functions like array_diff(), array_intersect()
> etc use weak comparison.
>
>
That's not quite correct. Using the example of array_diff, the comparison
is a strict equality check on a string cast of the values. So
array_diff([""], [false]) will indeed be empty
but array_diff(["0"],[false]) will return ["0"].

Tbh any use case for whatever array function but with strict comparison is
such an easy thing to implement in userland[1] I'm not bothered about
supporting it in core. But that's just me. I don't generally like the idea
of adding new array_* or str_* functions to the global namespace without
very good cause. There is a precedent for it though, in terms of changes
which have gone through in PHP 8, such as array_is_list or str_starts_with.

[1] Example:

function array_diff_strict(array $array1, array ...$arrays): array
{
$diff = [];
foreach ($array1 as $value) {
$found = false;
foreach ($arrays as $array) {
if (in_array($value, $array, true)) {
$found = true;
break;
}
}
if (!$found) {
$diff[] = $value;
}
}
return $diff;
}


Re: [PHP-DEV] [Discussion] Variable Type Declaration Before Usage

2023-11-05 Thread David Gebler
On Sun, Nov 5, 2023 at 1:37 PM Oladoyinbo Vincent 
wrote:

> Hello Internals,
>
> I was wondering if php could introduce this feature or if any experienced C
> dev here can work on the implementation of this feature.
>
>
I think this is a much bigger issue than bikeshedding over syntax. The idea
of typed variables has been discussed a few times in recent years but the
roadblocks have been efficiency of any possible implementation, BC in
respect of places type hinting can already be used and the overall
usefulness / desirability of the feature. It's one of those things that's
been filled in reasonably well by third party static analysis tools. Tbh
I'd be more interested in an official static analyzer than more type checks
at runtime.


Re: [PHP-DEV] RFC Proposal: Readonly Structs in PHP

2023-09-08 Thread David Gebler
On Fri, Sep 8, 2023 at 2:12 PM Lanre Waju  wrote:

> Dear PHP Internals,
>
> I am writing to propose a new feature for PHP that introduces the
> concept of structs. This feature aims to provide a more concise and
> expressive way to define and work with immutable data structures. Below
> is a detailed description of the proposed syntax, usage, and behavior.
>
> Syntax
>
> struct Data
> {
>  string $title;
>  Status $status;
>  ?DateTimeImmutable $publishedAt = null;
> }
> The Data struct is essentially represented as a readonly class with a
> constructor as follows:
>
>
> readonly class Data
> {
>  public function __construct(
>  public string $title,
>  public Status $status,
>  public ?DateTimeImmutable $publishedAt = null,
>  ) {}
> }
>

These as the most basic examples of what you're proposing are barely
different expressions in length, let alone anything else. I wouldn't say
the first example is particularly more helpful, more readable, more concise
or conceptually more expressive than the second. The rest of your examples
are similarly either very minor savings of a few characters shaved off here
and there, or just as verbose as instantiating a class with a constructor
anyway.

I'm not convinced by the rationale that this would be a new feature
worthwhile for improved expression or concision. I can see a potential
benefit in these "structs" (not sure that's the term//keyword I'd choose,
given it has different meanings in other languages) though, as a kind of
template for properly structured arrays, with a built-in ability to cast
them to arrays or treat them as arrays/iterables. This would potentially
help give some of the power we're missing by not having generics. So it
wouldn't just be equivalent to a shorthand for a readonly class with a
constructor, but one which also satisfied a couple of interfaces with the
implementation automatically provided.

That's my initial reaction/two cents.

-Dave


Re: [PHP-DEV] New reflection methods for working with attributes

2023-07-25 Thread David Gebler
What's the difference between this and what was proposed in
https://externals.io/message/120799 ? I don't get why this wouldn't require
an RFC.


Re: [PHP-DEV] Security implications of parsing env variables in .ini

2023-07-14 Thread David Gebler
On Fri, Jul 14, 2023 at 3:08 AM Dusk  wrote:

> 2) These expansions should probably be disabled by INI_SCANNER_RAW; that
> flag already disables certain other types of value interpolation. (Oddly,
> it doesn't disable expansion of constants either; that might be worth
> revisiting as well.)


Environment variable parsing is already disabled by INI_SCANNER_RAW mode,
isn't it? Personally I don't think the default/normal mode should behave
differently. If you're passing untrusted input to parse_ini_string, you
should be sanitizing, white listing or using raw mode anyway really.


Re: [PHP-DEV] Security implications of parsing env variables in .ini

2023-07-13 Thread David Gebler
On Thu, Jul 13, 2023 at 10:25 PM Sergii Shymko  wrote:

> For instance, functions parse_ini_string() and parse_ini_file() do support
> the aforementioned env variables syntax, because the underlying code is
> reused. That means that these functions can potentially be exploited to
> read sensitive information!
>
> For example:
> AWS_SECRET_ACCESS_KEY=amazonWebServicesSecretAccessKeyExample1 php -r
> 'var_export(parse_ini_string("secret=\${AWS_SECRET_ACCESS_KEY}"));'
> array (
>   'secret' => 'amazonWebServicesSecretAccessKeyExample1',
> )
>

If you find any way to exploit this, you've already breached enough to
have sufficient access to read the entire environment available to the PHP
user anyway (for example, you already had a way to inject arbitrary code
into a script which is eval'd or whatever...) in which case, why would you
care about parse_ini_string when you could just e.g. var_dump(getenv())?


Re: [PHP-DEV] [VOTE] Interface Default Methods

2023-07-12 Thread David Gebler
On Wed, Jul 12, 2023 at 5:01 AM G. P. B.  wrote:

>
> Maybe the resistance to the proposal would be far less if the RFC, and
> implementation, would check at compile time that the default
> implementations only rely on known existing functions available to the
> interface.
>

I asked in the discussion if this was a possibility, and it's the biggest
concern I had about the feature as proposed. Rowan answered "As the RFC
says, it introduces a form of multiple inheritance, and inheritance in PHP
doesn't make any such guarantee" and Levi added "I hope static analysis can
fill the gap here, but don't think these checks are necessary to ship this
feature" - and this is fair enough, I think; we kind of do accept the
nature of PHP is that there is some anti-intuitive weirdness versus
statically compiled languages. I wasn't convinced at first but I've come to
be persuaded even if it's not a perfect implementation of default methods
as I would have wanted them, it's still a significant improvement on the
trait + interface model we have now. It's ultimately a step in the right
direction and I'm disappointed now it looks like it's not going to happen,
at least in the next release. Would be good to know from some of the no
votes if they'd reconsider for a future version.


Re: [PHP-DEV] [VOTE] Interface Default Methods

2023-07-11 Thread David Gebler
Looks - sadly to me - like this isn't going to pass. I don't have vote
karma and if I did it wouldn't make a difference to the outcome, but it
would be really good for those of us who can't vote on the feature to hear
from some of the people who voted against it why they chose no. The
feedback from the discussion here seemed overall positive. It's one of
those things that's just a bit opaque to me, that quite often I see people
voting no on an RFC and we haven't heard from them in the relevant
internals threads, so we just never know why something was rejected or what
the author could have said or changed in the RFC to persuade them.


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

2023-07-04 Thread David Gebler
On Tue, Jul 4, 2023 at 8:30 PM Nuno Maduro  wrote:

> Hi Internals,
>
> I am writing to request karma privileges to vote on PHP RFCs.
>
>
I'm not a voter and have no influence here but from previous discussions
which have come from similar requests, I don't think you're likely to get
this. The conventional or common view is that without a regular history of
contributions to internals, both via this mailing list and proposing,
designing, implementing, fixing or otherwise aiding with RFCs, voting
rights are not typically granted. And even whether those criteria are
sufficiently met is a somewhat subjective thing.

I do think the system and criteria for choosing who gets to vote is
something which needs to be modernised and changed, particularly in respect
of recognising significant userland authors and contributors, but the
problem is probably that whenever this has come up before, no one's been
able to propose a sufficiently agreeable solution. We probably all share a
general principle of belief that PHP should be as open a democracy as is
practical, but there must also be a consideration for the fairly small
group of regular, core developers who are responsible - voluntarily - for
the majority of the work maintaining the new features which work their way
in.

I appreciate this is therefore not a straightforward matter, even though
like anyone else I'd like to be able to have a say in the future of the
language I love and use every day. I think the best thing there and what I
try to do myself is just make sure your voice is heard on this mailing list
on the discussion period of any RFCs which interest or concern you. This
mailing list is open, anyone can participate, no special karma needed. I've
had one small RFC and a couple of minor bugfixes accepted too. So we know
it's possible to give something back at whatever level and to whatever
extent we are able and willing, and we don't need to be able to vote to do
that.

-Dave


Re: [PHP-DEV] [RFC] Interface Default Methods

2023-06-20 Thread David Gebler
On Tue, 20 Jun 2023, 04:10 Levi Morrison,  wrote:

> > I like the idea of this RFC - in fact it's one which has been near top of
> > my wishlist for PHP language features for a long time - but I think this
> is
> > an issue with the proposed implementation which at the very least
> warrants
> > highlighting and discussion.
>
> I understand your concern but personally believe it's overblown. This
> problem already exists with abstract classes, but doesn't seem to be
> that much of an issue in practice. I hope static analysis can fill the
> gap here, but don't think these checks are necessary to ship this
> feature.
>


Yeah I suppose I'm just saying "Interface default methods" can be
interpreted a few different ways and there's key differences between
Java-style, versus syntax sugar for mixing an interface and a trait in to
one unit, versus a user can effectively extend multiple abstract classes
but with interface keyword.

Appreciate it appears to still be a WIP and you may not have decided or
designed all the finer details yet but I think at the very least, the RFC
text needs to be updated as soon as practical to be much more explicit
about these details so voters know exactly what they're voting on when the
time comes.

Cheers.

>


Re: [PHP-DEV] [RFC] Interface Default Methods

2023-06-19 Thread David Gebler
On Mon, Jun 19, 2023 at 9:53 PM Rowan Tommins 
wrote:

> On 19/06/2023 20:20, David Gebler wrote:
> > Okay, thanks. That's really quite significant, since it changes the
> feature
> > to one which could allow changes made to interfaces to adversely impact
> > existing clients of an interface without those clients changing a thing.
>
>
> As the RFC says, it introduces a form of multiple inheritance, and
> inheritance in PHP doesn't make any such guarantee - to adapt your example:
>
> class A {
>  public function foo(): void {
>  $this->bar();
>  }
> }
>
> class B extends A {
>  public function bar(): void {
>  ...
>  }
> }
>
> The job of detecting that class A doesn't define a contract for method
> bar falls to static analysers, and the same would be true for default
> implementations on interfaces.
>
>
>
>
Sure, but in this example were B::bar() to be a private method, you would
get a scope violation error. You would not if you were to use a trait,
since any methods implemented in the trait would be executed in the same
scope as the class using the trait. And that seems to be what's being
proposed here for interface defaults. So my concern here is that when you
use a trait, you know that what you're doing is effectively
copy-and-pasting implementation into your class scope. You don't expect
that when you declare a class to implement an interface.

There's some degree of irony to me that we have another RFC, the Override
attribute, which will introduce an engine-level check that could easily
(and arguably should) be left to static analysis tools, yet we're talking
here about introducing a mechanism where private methods on a class could
be called by stealth by a mere interface. I'm not even sure static analysis
tools would in their typical configuration pick up on a situation like
this, either, since it could in this scenario sit in a vendor dependency
and not your own code.

I like the idea of this RFC - in fact it's one which has been near top of
my wishlist for PHP language features for a long time - but I think this is
an issue with the proposed implementation which at the very least warrants
highlighting and discussion.


Re: [PHP-DEV] [RFC] Interface Default Methods

2023-06-19 Thread David Gebler
On Mon, Jun 19, 2023 at 3:53 AM Levi Morrison 
wrote:

>
> No, there's no attempt to ensure the method body adheres to calling
> the public interface. Due to PHP's possible dynamic behaviors, I don't
> think it's reasonable to attempt to enforce it at compile-time. I'm
> not sure it's worth the effort trying to enforce it at runtime either,
> but it would be nice to see lints from static analysis tools which
> detect this issue.
>

Okay, thanks. That's really quite significant, since it changes the feature
to one which could allow changes made to interfaces to adversely impact
existing clients of an interface without those clients changing a thing.

I was excited by the description of the RFC, but I was imagining something
more like how Java does it. Personally, this limitation (or rather lack of
it) is enough that I wouldn't support it and I'd urge anyone who can vote
to carefully consider the implications of the implementation being proposed.


Re: [PHP-DEV] [RFC] Interface Default Methods

2023-06-17 Thread David Gebler
On Thu, Jun 15, 2023 at 4:48 AM Levi Morrison via internals <
internals@lists.php.net> wrote:

>
> I am moving my RFC for interface default methods to discussion:
> https://wiki.php.net/rfc/interface-default-methods.
>
>
Can I ask, the RFC doesn't say - does your implementation ensure default
implementations can only call other methods which exist on the interface in
the same manner as Java? i.e. the following would give some sort of error?

interface A {
public function foo(): void {
$this->bar();
}
}

class B implements A {
public function bar(): void {
...
}
}

But the following would be okay?

interface A {
public function foo(): void {
$this->bar();
}

public function bar(): void;
}


Re: [PHP-DEV] RFC [Concept] - Interface Properties

2023-05-28 Thread David Gebler
On Sun, May 28, 2023 at 5:03 PM Larry Garfield 
wrote:

> On another level, I'd redefine properties and methods slightly.  (Public)
> Properties are not "raw data" but "aspects of the object I can manipulate"
> and methods are "behaviors I can ask the object to perform."
>

I just wanted to pull out this sentence in particular because I think it's
very much true of the property hooks RFC where you can attach behaviours to
what are from the outside accessed as if they were fields - and yes
properties on interfaces makes at least more sense in that case...but I
don't think it's true of the RFC Nick is proposing, which would very much
allow interface designs where a property is simply a (maybe typed) public
property and does represent a "raw data" value.

I suppose the difficulty for me is that I appreciate "people could abuse
it" isn't a reason in itself to exclude a feature, where it could prove
useful in a non-abusive way. But languages have ecosystems and frameworks
and conventions and idioms around them which go beyond what the language
strictly does and doesn't permit. People who like Laravel will say you can
write poor PHP code in any framework and good PHP code in Laravel, and
they're right, but personally I'd argue Laravel encourages you to write PHP
code in a way which is commonly and conventionally considered to not be a
best practice. And I don't like it very much for that reason. It's the same
for me with properties on interfaces; I think it will encourage people to
do things that some of the conventional wisdom out there says they probably
shouldn't.

Anyway, apologies I'm not replying in depth to your comments; I'm just wary
of descending into a philosophical wayside about principles of programming
and "best practices". And my views on those things are probably quite
anodyne, but the margin for difference in good opinions is more than enough
that I don't want to go there.

-Dave

On Sun, May 28, 2023 at 5:03 PM Larry Garfield 
wrote:

> On Sun, May 28, 2023, at 6:52 AM, David Gebler wrote:
> > On Sun, May 28, 2023 at 10:33 AM Rowan Tommins 
> > wrote:
> >
> >> I don't follow. If a property is public, then code outside the class can
> >> rely on being able to access it. That seems to me to be a contract
> between
> >> the class and its users, not an implementation detail - e.g. removing
> the
> >> property, or changing its type, would be a compatibility break. A
> property
> >> can also be inherited from a base class, at which point there is a
> contract
> >> that all descendants of that base class will have the property
> available.
> >> So it seems logical that that contract could also be included in an
> >> interface.
> >>
> >>
> > That's why you can declare constants in an interface (a static final
> > property, to use the lexicon of Java) which we can already do in PHP. At
> > the point you want to bring mutable state into an interface, it's a
> design
> > smell that what you want, really, is an abstract class or perhaps
> > composition.
>
> Almost never is an abstract class what you want, frankly.  An abstract
> class unnecessarily conflates "is a special case of" and "reuses code from"
> into a single syntax.  "Making one thing do two things" is a design flaw in
> most of computer science, and one that PHP has been bitten by multiple
> times.
>
> cf: https://www.garfieldtech.com/blog/beyond-abstract
>
> > A couple of languages do allow mutable properties on interfaces,
> TypeScript
> > being one of them, so yes it's not an unheard of feature - but in TS/JS
> > it's a lot more idiomatic to directly access properties than it is in
> PHP.
> > I'm not too familiar with C# personally but I have a vague recall that
> the
> > idea of properties on interfaces there is more akin to the property hooks
> > RFC than Nick's proposal here. And although I'm a little uncomfortable
> with
> > encouraging getters and setters on interfaces, I'm fully behind property
> > hooks, I hope that RFC passes.
> >
> > PHP already has the sufficient design tools to follow SOLID principles
> and
> > established design patterns well. If this RFC was in the language
> tomorrow,
> > you wouldn't be able to do anything you can't already do and do more
> > safely, more robustly, with behavioural interfaces and traits.
> >
> > -Dave
>
>
> There's technically nothing you cannot do with any language once it has
> type definitions, functions, and closures.  Everything beyond that is
> syntactic sugar; including classes themselves.  It's a question of which
> syntactic sugar gives the sweetest developer experienc

Re: [PHP-DEV] RFC [Concept] - Interface Properties

2023-05-28 Thread David Gebler
On Sun, May 28, 2023 at 10:33 AM Rowan Tommins 
wrote:

> I don't follow. If a property is public, then code outside the class can
> rely on being able to access it. That seems to me to be a contract between
> the class and its users, not an implementation detail - e.g. removing the
> property, or changing its type, would be a compatibility break. A property
> can also be inherited from a base class, at which point there is a contract
> that all descendants of that base class will have the property available.
> So it seems logical that that contract could also be included in an
> interface.
>
>
That's why you can declare constants in an interface (a static final
property, to use the lexicon of Java) which we can already do in PHP. At
the point you want to bring mutable state into an interface, it's a design
smell that what you want, really, is an abstract class or perhaps
composition.

A couple of languages do allow mutable properties on interfaces, TypeScript
being one of them, so yes it's not an unheard of feature - but in TS/JS
it's a lot more idiomatic to directly access properties than it is in PHP.
I'm not too familiar with C# personally but I have a vague recall that the
idea of properties on interfaces there is more akin to the property hooks
RFC than Nick's proposal here. And although I'm a little uncomfortable with
encouraging getters and setters on interfaces, I'm fully behind property
hooks, I hope that RFC passes.

PHP already has the sufficient design tools to follow SOLID principles and
established design patterns well. If this RFC was in the language tomorrow,
you wouldn't be able to do anything you can't already do and do more
safely, more robustly, with behavioural interfaces and traits.

-Dave


Re: [PHP-DEV] RFC [Concept] - Interface Properties

2023-05-27 Thread David Gebler
On Sat, May 27, 2023 at 9:44 PM Zoltán Fekete 
wrote:

> Abstract class could help this but it’s like using a
> tube wrench for a nut. Also one class can extend only one abstract class.
> By
> simply defining interfaces with properties would save a lot of boilerplate
> code
> and there would be no need for all the transferring from class A to class
> B with
> exactly the same properties.
>

Interfaces (as they are) and traits describe one of the possible solutions
you can use there.


> Why would it be a break of encapsulation? Having the `getSomething` and
> `setSomething` methods or the hooks are essentially the same as if just we
> have have the public property there. Just less code will be written.
>

I would say getters and setters don't [as a rule-of-thumb] really belong on
interfaces, since they by definition relate to properties of an object and
properties are by definition an implementation detail.

I don't want to get into a debate about principles of OOP and design
practices, this list isn't the place for it. I don't want to sidetrack the
discussion. I suppose what an interface should conceptually be in PHP is
necessarily relevant to whether or not one supports this proposal, though.

So yes anyay, my view is that between interfaces as we have them today,
traits and abstract classes, there isn't a problem which needs to be solved
by now allowing properties on interfaces, but it would open up a likelihood
of encouraging things which are often regarded as anti-patterns.

-Dave


Re: [PHP-DEV] RFC [Concept] - Interface Properties

2023-05-27 Thread David Gebler
On Sat, May 27, 2023 at 6:24 PM Larry Garfield 
wrote:

> On Sat, May 27, 2023, at 1:39 AM, Nick Humphries wrote:
> > Hello internals,
> >
> > Based on a few discussions I've had recently, my team and I couldn't
> > think of any reason why we shouldn't have properties on interfaces as
>
>
I wouldn't support this, personally. The reason interfaces in most
languages which have this concept don't support defining properties is
first because they are generally seen as an implementation detail rather
than a promise about supported behaviour and second because interfaces are
essentially an alternative to multiple inheritance. At the point you're
mandating fields as well as method signatures, you're barely one step away
from an abstract class anyway. If you still want to combine interfaces with
shared properties or default implementations, we already have traits for
that purpose. In PHP, two interfaces which define the same method signature
can be implemented by the same class, which is at least a little bit iffy
in itself. It becomes even more problematic if multiple interfaces can
define the same property, because you now don't really know
what, conceptually, that property refers to.


> Interface properties are already included in the Property Hooks RFC, which
> should be going to a vote soon-ish.  We hope it passes, of course. :-)
>
> https://wiki.php.net/rfc/property-hooks


For the reasons I've said, I'm not loving the interface part of the
property hooks RFC either, to be honest, though I do support the broad
feature. I can appreciate that when an interface is used with the hooks,
it's more akin to saying an interface is defining setSomething() and
getSomething() methods rather than defining a property directly - but it
feels like it will encourage writing interfaces which break encapsulation.

-Dave


Re: [PHP-DEV] RFC [Discussion]: Marking overridden methods (#[\Override])

2023-05-23 Thread David Gebler
On Tue, May 23, 2023 at 9:27 PM Tim Düsterhus  wrote:

> Just to make sure there is no misunderstanding I'd like to clarify that
> the proposed check of this RFC is not a runtime error. It's a compile
> time error, just like the check for incompatible method signatures
> during inheritance. In fact it shares a non-trivial amount of the
> existing logic of that check, because it's so similar.
>
> My understanding is that once the class is successfully sitting in
> Opcache there will not be any further overhead.
>

I figured as much, I say runtime just to differentiate from compiled
languages with a similar feature. Although OPcache is ubiquitous in
production environments now, it's not obligated and the cache only lasts as
long as the SAPI process. It's not overhead I think is the issue, anyway -
at least not off adding "one more thing" at this stage, it's more the
precedent of is there a sufficient benefit to adding this and potentially
more features like it at the language-level.

Merely delineating intent isn't something I feel warrants a change in the
language, particularly when you'd need SAs and IDEs to implement it anyway
for users to not be caught out with a fatal error at runtime (/compile
time).
Don't get me wrong; *delineating intent is a good thing*. I entirely get
where you're coming from, however I'd refer back to my earlier comment: any
attributes added in the engine should provide a tangible benefit which
*can't be achieved in userland*.


> I'll put the email back on unread and hope to
> be able to give a more expanded and nuanced reply later.
>

Do this if you feel it's beneficial to the wider audience of internals to
better understand the motivation and justification for your proposal, but
ultimately it's not me you need to persuade so certainly don't worry about
getting into further nuances on my account.

I don't have any more feedback or thoughts for you until/unless the RFC
changes, so I'll finish by saying for me, I'd either back Marco's
suggestion of try it as a plugin for PHPStan first, or expand your proposal
more along the lines of what Sara's suggested.

Thanks.

-Dave


Re: [PHP-DEV] rounding integers

2023-05-22 Thread David Gebler
On Sun, May 21, 2023 at 4:21 PM Larry Garfield 
wrote:

>
> Having recently been bitten by floor() returning a float even though the
> value that comes back is logically an int, I would be fully in support of
> "and returns an int" versions of these functions in core.
>

What about adding a third, optional parameter to round() which is a flag
(or bitmask) to specify preferred behaviour and return type? Kind of ugly,
but maybe less ugly than another new function and no BC-break, as the
default can be the existing behaviour.

-Dave


Re: [PHP-DEV] RFC [Discussion]: Marking overridden methods (#[\Override])

2023-05-22 Thread David Gebler
On Mon, May 22, 2023 at 1:01 PM Dan Ackroyd  wrote:

> Even for those who use static analysis, most (afaik) don't have it
> running constantly in local development and this RFC would prevent
> people wondering why their code is behaving surprisingly before it is
> static analysed.
>

It takes care of one possible surprise they might encounter as a result of
not running static analysis of their code prior to runtime. Just one, out
of dozens of possible types of inference which are done by static analysis
checks and could hypothetically be done by PHP at runtime. But I'd question
whether there's an appetite out there in general to start adding all sorts
of new runtime checks, which I would argue means any new runtime check
warrants the utmost consideration of cost-benefit.


> Also, not everyone uses static analysis tools.
>

That's because PHP is a dynamic language which doesn't have an explicit
compilation step and by extension where static analysis of any sort is
optional. That's my question around the benefit with this RFC; either you
use static analysis tools as part of your PHP workflow, because you care
about that stuff, or you don't. If you do, you don't need any new error or
warning emitting behaviour added to the engine itself, you just need
PHPStan / Psalm / IDE / whatever to flag it. If you don't habitually use
these tools already, you're probably not going to be annotating your code
with #[Override] anyway.

My wager is the kind of people and teams who would be most interested in
using and would benefit most from an #[Override] attribute are the kinds of
people who are using static analysis tools and probably have configured
PHPStorm / other IDE of choice to run those checks when a file changes, or
via commit hook, or build pipeline, or whatever else. What I see here,
then, is a perfect candidate for a userland attribute.

Anyway, usual disclaimer applies; I'm not a voter on RFCs, I'm one man with
an opinion, my opinion only matters insofar as gathering a range of
community feedback matters to the author and interested members of
internals.

-Dave


Re: [PHP-DEV] RFC [Discussion]: Marking overridden methods (#[\Override])

2023-05-20 Thread David Gebler
On Thu, May 18, 2023 at 9:12 AM Marco Pivetta  wrote:

>
> Would it perhaps make sense to have this in userland first, in phpstan or
> psalm plugins, to see if there is interest?
>

100% this in my view; this is exactly the kind of check which you would
expect to be done at the static analysis stage and I don't see a benefit to
new behavior in the engine here. Allowing us as PHP users to add whatever
kind of metadata and tooling to interpret it we find useful is exactly what
user-defined attributes are for. So any attributes added in the engine
which declare some behavioural change should be limited to those able to
provide a tangible benefit which can't be achieved in userland.

-Dave


Re: [PHP-DEV] [RFC] path_join function

2023-05-17 Thread David Gebler
On Wed, May 17, 2023 at 4:31 PM Chase Peeler  wrote:

> Definitely a useful feature, but not sure it needs to be a core function.
>
>
I feel the same. There are countless useful utility functions which could
exist in core, many of which are even widely used and commonly reinvented
as userland functions, Many would also seem at least prima facie to be
complementary to existing functions which are in core. But my understanding
of the usual convention is that "lots of people would have a use for it"
isn't enough where no significant further justification or benefit can be
provided for introducing a new core function.

On a wider philosophy on the future of the language, I'd be more inclined
to support changes like this which went the extra mile and introduced new,
complete object classes to group related core functionality and slowly
deprecate the enormous stock library of the global function namespace,
which feels random enough as it is.

-Dave


Re: [PHP-DEV] [Discussion] Callable types via Interfaces

2023-04-20 Thread David Gebler
On Thu, Apr 20, 2023 at 6:25 PM Larry Garfield 
wrote:

> ## The options
>
> There's three ways we've come up with that this design could be
> implemented.  In concept they're not mutually exclusive, so we could do
> one, two, or three of these.  Figuring out which approach would get the
> most support is the purpose of this thread.
>

My initial feelings based on the options laid out is that anything which
can't support FCCs in the manner of strlen(...) is probably a non-starter
in terms of language design. Changes like this are fundamentally about
making things simpler, more concise and more convenient for users, not
drip-feeding a stream of "and here's yet another way of working with..."
features across releases.

Structural typing option seems like the easiest to implement in the engine
(correct me if I'm wrong?) and probably the best syntax for the user within
the interface approach. But then do we really want to introduce new runtime
checks and complexity when the general trend of the language has been in
the opposite direction? I imagine probably not.

So out of the three, I lean towards adding castTo() to Closure and it maybe
raises a to-be-determined Throwable if the closure is already bound? It's
not as friendly for the user as the other options but it seems like the
most workable, it delivers value and it most closely fits within the
existing way of working with all types of closure today.

-Dave


Re: [PHP-DEV] base64url format

2023-01-09 Thread David Gebler
On Mon, Jan 9, 2023 at 9:42 PM Derick Rethans 
wrote:

> On 9 January 2023 18:49:28 GMT, Sara Golemon  wrote:
> >I've been working with JWTs lately and that means working with Base64URL
> >format. (Ref: https://www.rfc-editor.org/rfc/rfc4648#section-5 )
> >This is essentially the same thing as normal Base64, but instead of '+'
> and
> >'/', it uses '-' and '_', respectively. It also allows leaving off the
> >training '=' padding characters.
> >
> >So far, I've just been including polyfills like this:
> >
> >function base64url_decode(string $str): string {
> >return base64_decode(str_pad(strtr($str, '-_', '+/'), (4 -
> >(strlen($str) % 4)) % 4, '='));
> >}
> >
> >function base64_encode(string $str): string {
> >return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
> >}
> >
> >These work fine, but they create a LOT of string copies along the way
> which
> >shouldn't be necessary.
> >Would anyone mind if skipped RFC and just added `base64url_encode()` and
> >`base64url_decode()` to PHP 8.3?
>
> Should these be new functions, or options to base64_encode instead? I'd
> guess base64_decode could just accept both?


I think from a UX/DX perspective, separate functions would be my
preference, base64_url_encode and base64_url_decode (extra underscore which
I feel is more consistent with PHP stock library). One consideration though
is that base64_urlencode or base64_url_encode are function names which are
likely already defined by a number of userland projects or libraries, since
it's a very common thing to do with the prevalence of JWTs, so if the RFC
process is being bypassed in this case, a new optional parameter to
base64_encode might be better. But I think it would be weird to have
base64_encode(bool $urlEncode = false) or something, which is presumably
what it would look like.

Dare I float the suggestion of a Base64 class, making base64_encode and
base64_decode functions aliases for Base64::encode() and Base64::decode()
respectively, then new Base64::urlEncode() and urlDecode() methods?


Re: [PHP-DEV] Revisiting RFC: Engine Warnings -- Undefined array index

2022-12-13 Thread David Gebler
On Mon, Dec 12, 2022 at 10:20 PM Dan Liebner  wrote:

> As the RFC points out, "Some languages, such as JavaScript, do not consider
> accesses to undefined array keys to be an error condition at all, and allow
> such an operation to be performed silently."
>

It is by definition an error condition though. You're trying to access
something which doesn't exist.


>
> For the last 20 years, it's been my impression that PHP also embraced this
> philosophy, and that raising an E_NOTICE for "Undefined index" was more or
> less offered as a debugging tool, as a matter of practicality.
>

In the earlier days of PHP, it was more acceptable to allow garbage in
scripts. Generally, the community consensus has been that trending away
from that has been a positive.

It's strongly arguable that E_NOTICE was never appropriate for undefined
array index access, since it is not really something which can occur in
"the normal course of running a script" (since it necessarily means your
script is broken).


>
> JavaScript returns the undefined primitive for accesses to undefined array
> and object keys. PHP returns the NULL primitive respectively despite
> raising an error.
>
> Here's my biggest criticism: the change essentially forces this:
> $arr['key']
>
> to be rewritten as this (or some other intolerably bad alternative):
> isset($arr) && isset($arr['key']) && $arr['key']
>
> This is a major regression in my opinion as far as productivity and
> readability are concerned.
>

It seems strange to quibble about readability and syntax when you're
talking about a situation in your code which is by definition an error
condition. Accessing something which doesn't exist isn't the same as
accessing something which does exist and it not having a value (i.e. the
value is a null).

Null = "Can I have the address for this customer please?", "No sorry, we
don't have an address on file for them.
"Undefined = "Can I have the gooble-gabble for this customer please?", "The
what?"

But sure, we don't always have a guarantee about the structure of some
data, especially in web where input usually comes from an HTTP request
which may or may not contain anything. But in those situations we can check
instead of making assumptions.

Good = "Hey, just checking, do we have something called gooble-gabble on
file for this customer?", "Sure, here it is" for one customer, "No, sorry
that's not a thing" for another (this is your array_key_exists / isset /
null coalesce / whatever)

Bad = "Can I have the gooble-gabble for this customer please?", "Sure, here
it is" for one customer, "The what?" for another


>
> It has been proposed to make the error level of "Undefined index"
> configurable so that teams and individual developers can decide for
> themselves how they want this situation to be handled.


There's a much better way of allowing developers to decide for themselves
how to handle the gooble-gabble situation in a future major release; have
undefined index access throw an UndefinedIndexError which can be caught.

Then we can say

"Can I have the gooble-gabble for this customer please? And if
gooble-gabble isn't a thing, no problem, I can deal with that"

That's my two cents, cheers.


Re: [PHP-DEV] Experimental features

2022-10-10 Thread David Gebler
On Tue, Oct 11, 2022 at 12:05 AM David Rodrigues 
wrote:

> The idea is that the experimental features are exclusively something that
> the PHP team has voted for (approved) and that will be part of the language.
>

So they're not experimental features, they're accepted RFCs, maybe with a
lower voting threshold.


> Imagine a package under development (eg. Laravel 10) that is (supposing
> that) intended to be released compatible with PHP 8.3 (supposing that it
> already has experimental features). In this case, the Laravel team can
> start using an experimental feature while developing Laravel 10, waiting
> for the release of PHP 8.3. Once the PHP 8.3 release is finished, Laravel
> 10 can just remove the experimental tags and release its new version fastly.
>
> The user, on condition that he is willing to use Laravel 10 (in
> development) will make indirect use of experimental features. Then both the
> Laravel team and these users will be able to provide feedback for these
> features to the PHP team before the official release.
>
> Like json_validate(): assuming Laravel needs to check if a code is valid
> JSON, but without processing its data for use. It could check if PHP >=
> 8.3, so use experimental_json_validate(), else use previous PHP compatible
> code.
>

This is what's bothering me. Either these "experimental" features have
passed RFC and will be part of the language, as you've said above, or
they're actually experimental i.e. not finalized and implementing behaviour
and syntax which may be subject to change or even dropped entirely
depending on the feedback cycle. In which case, they cannot be relied on by
developers of vendor packages or their users in the manner you suggest.

Using the trivial json_validate() example (although as others have said, a
simple new function is probably a bad example), either this function will
be part of PHP 8.3, with the exact behaviour, parameters and return type
which is known and documented, or it's experimental and might change.

If it's the former, the library can just check if PHP >= 8.3 and fall back
to userland implementation / polyfill for earlier versions. This is just
what we have now, where approved new features are part of a versioned
release.

If it's the latter, everyone touching the experimental version, directly or
indirectly, may have to rip out and change code later which renders the
work they've put in to use the experimental feature in their code pointless.

And it's not just how these things may or may not be used by users of the
language, it's how building out this system affects the clarity and
maintainability of php-src, which is esoteric enough as it is.

I can appreciate and support specific individual new, accepted features
which may not be 100% stable having a toggle in the configuration, but I'm
not convinced on the justification for a broader system of introducing
unstable features which are toggled at the syntax level.

On Tue, Oct 11, 2022 at 12:06 AM Mike Schinkel  wrote:

> A lot of developers (most?) who build PHP applications run them in
> shared-hosted or managed hosted servers where are never given the option to
> install a PECL extension.

In the rare cases they can install PECL many of those PHP developers would
> not have the skills to do it or the requisite permissions on the server; I
> certainly did not for the first ~10 years of working with PHP. I do now,
> but ironically because I have mostly moved away from programming in PHP to
> do more DevOps work.
>

> Further, when working in multiple environments having to set up each
> server to have all the same PECL installations can be just too much hurdle
> so that developers won't even try, especially when working in managed
> environments.
>
>
I'm inclined to suggest if you opt in to an experimental language feature,
you are by definition making at least an implicit declaration that you know
what you're doing, so the idea people using these features wouldn't have
the skills to spin up a container or install something on a VM doesn't
convince me, personally.


Re: [PHP-DEV] Experimental features

2022-10-10 Thread David Gebler
My two cents...

Why can't "common users" install a PECL extension? It's not a difficult,
obscure or undocumented process.

I can accept the reasoning

> Apply a PECL strategy to try experimental features might not be the
convenient way always, for example, if we create a new ... sensitive ini
setting that affects the behavior of PHP somehow... OR ... what about a new
sensitive funtion in a "core extension" like JSON?

But why would the answer in those cases not be "compile the PHP fork/branch
with the experimental feature", rather than find a way to flag the engine
to switch arbitrary new features on or off, complete with all the
complications in the primary source code that would cause? We are, after
all, talking about features which by definition should not be relied upon
for any production use.

Or we're talking about features which are stable and valuable enough to
have passed an RFC process, but then what's gained from an experimental
designation? Why couldn't they just be included in a preview/beta/RC
version which anyone could decide to run or not?


Re: [PHP-DEV] Sanitize filters

2022-10-05 Thread David Gebler
On Tue, Oct 4, 2022 at 11:34 AM Rowan Tommins 
wrote:

> The "notorious" thing I know is that validating e-mail addresses is next
> to impossible because of multiple overlapping standards, and a huge
> number of esoteric variations that might or might not actually be
> deliverable in practice. If you think the implementation can be
> improved, that doesn't need a new is_valid_email() function, just a
> tested and documented patch to the existing one; if it can't be
> improved, then any new function will be just as useless
>

There are multiple RFC standards for email address format but AFAIK PHP's
FILTER_SANITIZE_EMAIL doesn't conform to any of them.

The idea behind my suggestion for something like is_valid_email (whatever
it might be named) is as a step towards deprecating and removing the entire
existing filter API, which I think many of us agree is a mess. As you said
below "it's trying to be everything to everyone, and ends up with a
bewildering set of options" - a rewrite or replacement which also tries to
be everything to everyone won't solve that problem, but getting rid of it
entirely will.

That said, the nature of PHP as a web-first language means it's reasonable
to include some individual, smaller, better APIs for certain validations or
sanitizations on types of data which are very commonly encountered in HTTP
requests. Examples include strings we expect or want to be valid integers,
decimals, email addresses and URLs. I think these features should remain,
but I'd happily see them even as a set of new, individual core functions if
it meant binning off filter_var and filter_input in PHP 9.

Regardless, look - I don't want to derail here - if most people are happy
with just deprecating some of the crappier and more confusing sanitize
filters and leave it at that, I say great, go for it, it's still an
improvement. I'm just saying if someone's going to take the time to look at
that problem space, why not go more than half the distance and reconsider
the fundamental approach of something we all know is pretty sucky anyway?

Just food for thought.


Re: [PHP-DEV] Sanitize filters

2022-10-03 Thread David Gebler
On Mon, Oct 3, 2022 at 11:29 AM Max Semenik  wrote:

>
> Is there a compelling need to have this in the core, as opposed to
> Composer packages? The ecosystem has changed a lot since the original
> function was introduced.
>

I don't know that there is, I suspect the answer is probably not and
sanitization and validation is probably better left to userland code. The
only argument I can offer as devil's advocate is that certain validations
or transformations will be faster in core than in library scripts. I would
wager the most common implementation of such userland libraries today are
heavily reliant on preg_* functions so having some fast, low level baseline
in core for common tasks in this category might still make sense.

While we're on the topic, can I bring up FILTER_SANITIZE_NUMBER_FLOAT? Why
is the default behaviour of FILTER_SANITIZE_NUMBER_FLOAT the same as
FILTER_SANITIZE_NUMBER_INT unless you add extra flags to permit fractions?
Why is the constant name FILTER_SANITIZE_NUMBER_FLOAT but its counterpart
for validation is FILTER_VALIDATE_FLOAT (no NUMBER_)? Why does validating a
float return a float but sanitizing a float return a string?

What about FILTER_VALIDATE_EMAIL which is notorious for being next to
useless?

Seems to me like there could at the very least be a plausible case for some
better to_float(), to_int(), is_valid_email() etc. type functions in core
to replace some of the filter API.


Re: [PHP-DEV] Sanitize filters

2022-10-02 Thread David Gebler
On Sun, Oct 2, 2022 at 4:10 PM Larry Garfield 
wrote:

> The filter extension has always been a stillborn mess.  Its API is an
> absolute disaster and, as you note, its functionality is unclear at best,
> misleading at worst.  Frankly it's worse than SPL.
>
> I'd be entirely on board with jettisoning the entire thing, but baring
> that, ripping out large swaths of it that are misleading suits me fine.
>
>
The whole thing is seriously grim. Looking at the documentation for
filter_var for example, look at what it says for the third parameter,
$options

>  Associative array of options or bitwise disjunction of flags. If filter
accepts options, flags can be provided in "flags" field of array. For the
"callback" filter, callable type should be passed.

At a glance, I think all the examples mentioned in this thread have better
existing alternatives already in core and could just be deprecated then
removed. But it's worth asking, is that what we're talking about here, or
is there a suggestion of replacing the filter API with a more modern,
object API?


Re: [PHP-DEV] Increase maximum size of an uploaded file to 50Mbyte

2022-09-10 Thread David Gebler
On Sat, Sep 10, 2022 at 3:05 PM juan carlos morales <
dev.juan.mora...@gmail.com> wrote:

> I also agree that increasing the size to something bigger than 8M
> might not be a good idea; I can imagine that a value bigger than 8M
> (like 50M) will cause an impact in hosting platforms specially, which
> will be forced to always change the php's default values to a lower
> one, because of potential DoS Attacks.
>
> Default settings should have a reasonable level of security in mind.
>

Do these settings actually have any impact in respect of DoS attacks? As
far as I'm aware, neither post_max_size nor upload_max_filesize do anything
to prevent or terminate processes where the client sends data exceeding
these limits, that's something you should handle in your webserver.


Re: [PHP-DEV] Re: Increase maximum size of an uploaded file to 50Mbyte

2022-09-07 Thread David Gebler
On Wed, Sep 7, 2022 at 10:47 PM Kris Craig  wrote:

> On Wed, Sep 7, 2022 at 11:38 AM juan carlos morales <
> dev.juan.mora...@gmail.com> wrote:
>
> > I looked for a potential problem out of doing such a change but I could
> not
> > find anything.
> >
>
> Then I'd say it's a no-brainer.  The current 2 MB limit is simply outdated
> and needs to be increased to something a little more realistic.
>
> That said, I think 50 MB may be pushing it.  How about 20 MB, instead?
>
>
That's the obvious question; why 50MB? Why not 10, 20 or [fill in the
blank]MB?
I have no objection in principle to increasing the shipped default but
whatever number is picked, most devops/sysadmins are going to change it to
suit their needs. I would classify this as an unnecessary but harmless
change, since you should be tuning your engine configuration in any public
facing deployment anyway.


Re: [PHP-DEV] RFC json_validate() - status: Under Discussion

2022-08-26 Thread David Gebler
Juan,
You can always offer two votes on the RFC - one for the function itself,
then one for should it return boolean or return an int representing the
json_last_error constants and let it be decided that way.

I think on the whole, I agree with the sentiment that returning boolean and
checking json_last_error() on false is probably the best / least worst
option.

So if I could vote, I would vote yes and for the boolean option, with a
secondary preference for returning int if boolean option is rejected.

And I was unconvinced about the whole idea originally, so a good example of
where positive, robust discussion can change someone's mind.

Good luck with progressing the RFC, I don't think I have anything else to
add.


On Sat, Aug 27, 2022 at 12:46 AM juan carlos morales <
dev.juan.mora...@gmail.com> wrote:

> OMG, I need to take a rest, sorry for this, here it goes again; the
> about JSON_INVALID_UTF8_IGNORE opinion is the same, but previous code
> was wrong
>
> Code:
>
> 
> var_dump(json_decode("{ \"a\xb0b\" : \"dummy\" }", true, 512),
> json_last_error_msg());
> var_dump("");
> var_dump(json_decode("{ \"a\xb0b\" : \"dummy\" }", true, 512,
> JSON_INVALID_UTF8_IGNORE), json_last_error_msg());
>
> Result:
>
> NULL
> string(56) "Malformed UTF-8 characters, possibly incorrectly encoded"
> string(12) ""
> array(1) { ["ab"]=> string(5) "dummy" }
> string(8) "No error"
>
> Saying so, now ... yes I support and think is NEEDED the usage of the
> JSON_INVALID_UTF8_IGNORE , as json_validate() result goes in the same
> direction with json_decode(). I think we need to have this flag.
>
> RFC: https://wiki.php.net/rfc/json_validate
> Implementation: https://github.com/php/php-src/pull/9399
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] RFC json_validate() - status: Under Discussion

2022-08-26 Thread David Gebler
On Fri, Aug 26, 2022 at 6:29 PM Kamil Tekiela  wrote:

> What is the reasoning behind the name? I can't find it explained in the
> RFC. What about other alternatives like is_json or validate_json?
>

The name json_validate makes most sense to me; it groups itself together
nicely with the other json_* API functions. I think is_json is what was
originally proposed but besides being then inconsistent with the rest of
the JSON API function naming, consider most of the is_* functions are for
checking types (and some for file properties), not validation.

But on the function, the other question which remains for me is whether
returning boolean is the right thing to do at all. It seems obviously
intuitive it should, returning true for valid and false for invalid JSON
but then if you consider you're still going to be in the situation of
calling json_last_error() if you want to know why invalid JSON was invalid
and in particular you might not expect the "last error" to have changed
just from an attempt to check a string. How can there be an error when by
definition you weren't trying to do anything except check the validity of
some unknown data? Not sure what the answer is there...curious what other
people's views are on that. I don't think throwing an exception on invalid
JSON is the right answer in any case.


Re: [PHP-DEV] RFC json_validate() - status: Under Discussion

2022-08-25 Thread David Gebler
Having actually compiled the branch and tried it out, I have to say
regardless of whether validating arbitrarily large blocks of JSON without
being interested in the contents is a common or more niche use case, the
memory savings ARE highly impressive. I had thought that because the
function was built on top of the existing parser and is still parsing the
entire string (or up until invalid JSON is encountered), the performance
saving for a very large input would be smaller than it is.

I tested using a 75MB valid JSON input - a string large enough that it's
not going to be very common. The processing time isn't hugely different,
the saving appears to be around maybe 20-25% (and it's not a significant
amount of time using either json_decode or json_validate, even on an input
of this size, about half a second on my machine for both). But the memory
saving is enormous, almost total. Gone from needing ~5x the size of the
input to almost literally just a few extra bytes.

I'm persuaded now on both that benchmarking and having had a closer look at
the implementation PR, which is clearly a minimal and easily maintainable
change.

As I've said, my feelings are irrelevant to the extent I'm not a voter, but
I am in principle a +1 thumbs up for including this now.


Re: [PHP-DEV] RFC json_validate() - status: Under Discussion

2022-08-25 Thread David Gebler
I'm not a voter on RFCs so my input may be largely irrelevant here but for
discussion purposes:

I remain unconvinced regarding the justification for this proposal. I'm not
saying there's a strong reason to NOT implement it, but I'm not convinced
it's really going to be a significant benefit to many people at all.

I agree that the number of userland implementations for a "is_valid_json"
type function including in some widely used frameworks and systems
indicates there's some degree of demand in the ecosystem for validating a
JSON string.

But the more salient question is whether there is a significant demand for
whatever memory and speed benefit the implementation of a new core ext_json
function delivers; that is, has it been established that the use of
json_decode or common userland solutions are in practice not good enough?

There are many examples of userland code which could be faster and more
memory efficient if they were written in C and compiled in, so the mere
fact this proposal may introduce a somewhat faster way of validating a JSON
string over decoding it is not necessarily a sufficient reason to include
it.

Are there are examples of raising issues for frameworks or systems saying
they need to validate some JSON but the only existing solutions available
to them are causing memory limit errors, or taking too long? The Stack
Overflow question linked on the RFC says "I need a really, really fast
method of checking if a string is JSON or not."

"Really, really fast" is subjective. No context or further information is
given about what that person would regard as an acceptable time to validate
what size blob of valid or invalid JSON, or why. Indeed that same page
offers a userland solution based around only going to json_decode if some
other much simpler checks on the input are indeterminate for validation
purposes. Haven't tested it personally but no doubt in the vast majority of
cases it is sufficiently performant.

In most real world use cases [that I've encountered over the years] JSON
blobs tend to be quite small. I have dealt with much, much larger JSON
blobs, up to a few hundred MB, and in those cases I've used a streaming
parser. If you're talking about JSON that size, a streaming parser is the
only realistic answer - you probably don't want to drop a 300MB string in
to this RFC's new function either, if performance and memory efficiency is
your concern.

So I'm curious as to whether a real world example can be given where the
efficiency difference between json_decode and a new json_validate function
would be important to the system, whether anyone's encountered a scenario
where this would have made a real difference to them.


Re: [PHP-DEV] Proposal for floored division and modulo functions

2022-08-23 Thread David Gebler
On Tue, Aug 23, 2022 at 6:27 PM Daniel Wolfe  wrote:

>
> If we do go down the operator route, however, what tokens should be
> chosen? `%%` makes since for floor modulo, but `//` is already used for
> comments.
>

Yeah I appreciate it is tricky, because // is pretty much the only
obviously sensible syntax for such an operator and it's unavailable.
I don't know what the objections were around an operator verus intdiv way
back then - maybe that was one of them, maybe people just didn't feel it's
something you do often enough to warrant an operator. Both valid objections
and likely to come up again if they came up before.

*shrug* nothing inherently wrong with your proposed functions being
functions, either, I can just see floor_div and floor_mod getting mixed up
with fdiv and fmod but maybe I'm overthinking it, maybe it wouldn't really
be an issue. Maybe there's alternative names you could give them though
again I suspect the ones you've chosen are the most obviously sensible to
describe what they do.

See what other people think - personally, I support the idea of having the
functionality to perform these operations, one way or another, supported in
the core, just because I think they are common enough scalar operations
that it's worth them being directly supported rather than being a third
party package.


>
> * 
>
>
>


Re: [PHP-DEV] Proposal for floored division and modulo functions

2022-08-22 Thread David Gebler
On Mon, Aug 22, 2022 at 4:22 AM Daniel Wolfe  wrote:

> For the first four instances, the function works as intended since the
> timestamps are non-negative numbers. However, for the fifth example,
> since the date is before 1970, the timestamp is going to be negative
> resulting in an ostensible array key which will also be negative. The
> floor technique would instead return a positive array key.
>
> …since the time of the day for each of these dates is the same (i.e.,
> 1:46 AM), it *should* calculate 6,360 seconds since midnight for each
> instance. It does this correctly for the first four instances, but the
> fifth instance reports -80,040 seconds—a meaningless result. The floor
> technique would return the same result as the others.
>

Both these examples and any others can already be solved very easily in
userland PHP, either ad-hoc specific to what you're doing or by user
implementations of floor_div and floor_mod. No doubt you are already aware
it's as simple as:

function floor_mod($a, $b)
{
return $a - ($b * floor($a / $b));
}

That said, while my preference is *usually* "don't add stuff to PHP which
users can easily do themselves", I do think in the case of certain
ubiquitous and useful scalar operations, there's a good case for it being
supported out the box. And this has been done, many times - functions like
str_contains and array_key_last were things which could be easily done in
userland and easily supported through polyfills for older PHP versions.

The bit I think I might not like is these being functions, floor_div and
floor_mod. They may be easily confused with the similarly named and
existing fdiv and fmod functions. Wouldn't new operators, // and %%
respectively, be preferable?

-Dave


Re: [PHP-DEV] RFC Idea - is_json - looking for feedback

2022-08-01 Thread David Gebler
On Sun, Jul 31, 2022 at 4:41 PM Larry Garfield 
wrote:

> So the core argument, it seems, is "there's lots of user-space
> implementations already, hence demand, and it would be
> better/faster/stronger/we-have-the-technology to do it in C."
>

There's innumerable features implemented in userland which would be
faster/stronger/better done in C. I'm not convinced this alone is a
sufficient basis to introduce a new core function. There are also userland
JSON streaming parsers which are memory efficient, I've used the one I
linked to parse JSON files over 1GB no problem.

And I'm not saying I'm against this proposal, I'm just covering devil's
advocate here - but while I can accept the number of userland
implementations for "validate string as JSON" out there clearly show some
demand / use cases for doing this, are there equally numerous examples of
issues raised on these product repositories demonstrating userland
implementations have commonly been insufficient, encountered OOM errors or
otherwise caused problems? This might be an RFC to fix a problem very, very
few people have.


>
> Thus another, arguably more important benchmark would be a C
> implementation compared to a userspace implementation of the same
> algorithm.  Presumably your C code is doing some kind of stream-based
> validation with braces/quotes matching rather than a naive "try and parse
> and see if it breaks."  We would need to see benchmarks of the same
> stream-based validation in C vs PHP, as that's the real distinction.  That
> a stream validator would be more memory efficient than a full parser is not
> at all surprising, but that's also not a fair comparison.
>
> As for the benchmarks themselves, do not use memory_get_usage(); as noted,
> it shows the memory usage at that time, not ever.  What you want is
> memory_get_peak_usage(), which gets the highest the memory usage has gotten
> in that script run.  Or, even better, use PHPBench with separate sample
> methods to compare various different implementations.  It will handle all
> the "run many times and average the results and throw out outliers" and
> such for you.  It's quite a flexible tool once you get the hang of it.
>
> I'll also note that it would be to your benefit to share the working C
> code as a patch/PR already.  If accepted it would be released open source
> anyway, so letting people see the proposed code now can only help your
> case; unless the code is awful, in which case showing it later would only
> waste your time and everyone else's discussing it in the abstract before
> the implementation could be reviewed.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] RFC Idea - is_json - looking for feedback

2022-07-30 Thread David Gebler
On Sat, Jul 30, 2022 at 3:01 PM Nikita Popov  wrote:

> On Fri, Jul 29, 2022 at 4:27 PM juan carlos morales <
> dev.juan.mora...@gmail.com> wrote:
>
> > I am following the RFC guideline for the first time. (
> > https://wiki.php.net/rfc/howto)
> >
> > As suggested there, I am here to get a feeling from you, regarding the
> > following RFC for PHP.
> >
> > # Change (draft):
> >
> > New function in php called like:
> >
> > is_json(string $string): bool
> >
> > ## Description
> > ### Parameters
> > string $string -> string to find out if is a valid JSON or not
> >
> > ### Return
> > Returns a bool. The function is capable to determine if the passed string
> > is a valid JSON (true) or not (false).
> >
> > # Why this function ?
> >
> > At the moment the only way to determine if a JSON-string is valid we have
> > to execute the json_decode() function.
> >
> > The drawback about this, is that json_decode() generates an in memory an
> > object/array (depending on parameters) while parsing the string; this
> leads
> > to a memory usage that is not needed (because we use memory for creating
> > the object/array) and also can cause an error for reaching the
> memory-limit
> > of the php process.
>

In the last 15 years, the only time I've ever needed to know if a string is
valid JSON is if I'm about to decode or otherwise parse it as JSON. If I'm
decoding what I expect to be a large JSON blob, such that memory usage
might be a concern, personally I use
https://github.com/salsify/jsonstreamingparser but the point is userland
solutions are possible.

What I'm asking is what's the practical use for this proposed function?
Where are you likely to need to know if a string is valid JSON but not have
to (try to, with error handling) parse it almost immediately afterwards
anyway? Unless there is some fairly commonplace use case for this I'm not
thinking of, you're going to be using that extra memory, or using a
streaming parser,  at some point in your script regardless. If there is
genuine demand for it, I'd be in favour (I'm not a voting member so kind of
moot but...), otherwise I'm generally against introducing new core
functions which are either edge-case or can be perfectly well dealt with
via userland code.

Cheers

-Dave


> >
> > Sometimes we just need to know is the string is a valid json or not, and
> > nothing else.
> >
> > # Do we need something like this? If a check to an string is valid JSON
> > then for sure I will have to use it in my code either as an object or an
> > array.
> >
> > Well that is not true. There are plenty of cases where you just need to
> > check if a string is a valid json and that is it. Just looking into
> > stackoverflow will give you an idea about how many people is looking for
> > something like this in an efficient way.
> >
>
> Could you please give some specific examples where the proposed
> functionality would be useful?
>
> Regards,
> Nikita
>


Re: [PHP-DEV] Adding new closing tag =?> for keeping trailing newline

2022-06-05 Thread David Gebler
On Sun, Jun 5, 2022 at 9:24 AM shinji igarashi  wrote:

> Hello everyone,
>
> I'd like to propose adding a new closing tag `=?>` to the language.
>
> PHP currently removes the newline character immediately following
> the closing tag `?>`.
>

Personal opinion, seems like a classic sledgehammer on a nut proposal. I
actually prefer the  or ."\n" notation since it
makes it explicitly clear what you're intending to output and keeps it
within the control of the PHP code block. Alternatively it's also enough in
the case of plain text or wherever else this matters to you to just add a
space after the closing tag before the newline (granted there may be niche
situations where this is undesirable).

It's not a breaking change for any existing code, at least, but for me I
still don't see enough of a benefit that I'd think it was worth adding to
the language, as any new syntax creates the potential for confusion and
user error. Is this a big enough problem to be worth any change at all? In
over 15 years of writing PHP, I've never once had a situation where closing
tag newline elision has been an issue.

-Dave


>
> With the new closing tag `=?>`,  the code should look like this:
>
> ```
> - 
> - 
> - 
> ```
>
> and the results it produces would be:
>
> ```
> - 1
> - 2
> - 3
> ```
>
> instead of the following:
>
> ```
> - 1- 2- 3
> ```
>
> This addition requires only a one-line modification to the lexer and
> doesn't break BC. The proposed patch is here.
> https://github.com/php/php-src/pull/8708
>
> Before writing an RFC, I would like to hear your input on whether
> it's worth tackling.
>
> Thanks!
>
> --
> Shinji Igarashi
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] RFC: Trait expects interface

2022-01-05 Thread David Gebler
On Wed, Jan 5, 2022 at 11:05 PM Larry Garfield 
wrote:

> On Wed, Jan 5, 2022, at 2:35 PM, Chase Peeler wrote:
>
> For point 2, that's mainly useful as a way to signal to other developers
> "hey, this trait has all but one method of the LoggerInterface, that's how
> you'd use it", and to signal static analyzers and refactoring tools the
> same thing so that they can be auto-updated if you tweak the interface.  I
> can see a use for point 2, and it would make my life a bit easier, but it's
> overall not high priority.
>
>
I think existing constructs provide 99% of this benefit anyway.

interface I { public function hello(); }
abstract class A implements I { abstract public function hello(); }
trait T { public function hello() { echo 'hello'; } }
class C extends A { use T; }
// or alternatively
class D implements I { use T; }
// or
abstract class E implements I { use T; }
class F extends E { ... }

$c = new C;
$c->hello(); // $c is instanceof I
$d = new D;
$d->hello(); // $d is instanceof I
$f = new F;
$f->hello(); // $f is instanceof I

It's not quite as neat as directly having a way of annotating T to say it
implements I, but it does the job insofar as your IDE and tools should be
able to immediately pick up a change in interface I is not fulfilled by
anything relying on trait T to be of type I, either directly or by
inheritance.

The remaining 1% of benefit could probably be achieved just by naming
convention:

interface LoggerInterface { ... }
trait LoggerInterface_FileLogger { ... }

But I still think both goals would be better achieved with something like:

interface LoggerInterface {
default public function error(string $message) {
$this->logger->log('error', $message);
}
}

in the manner of Java...no idea how easy or not it would be for someone a
little more experienced than me working on PHP core to do this though.

- David


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


Re: [PHP-DEV] RFC: Trait expects interface

2022-01-05 Thread David Gebler
On Tue, Jan 4, 2022 at 10:35 PM Kirill Nesmeyanov  wrote:

> How relevant do you think this idea/proposal is? And what possible
> problems or solutions will this entail in the future?
>

I'm not convinced there's a reasonable need for it. The very nature of
finding yourself in a situation where you want any class using a trait to
also require other things outside the trait kind of suggests you really
want to be using interfaces or abstract classes anyway.

There is a similar concept for what I think you're trying to achieve in
Java, though, which could also be useful in PHP if it was feasible within
the engine - the ability to provide a default method implementation on
interfaces themselves.

Short of that, we can already effectively get there with the tools we have;
an abstract class can use a trait and define abstract or concrete methods,
and in doing so can implement one or more interfaces. Obviously traits can
also declare abstract methods but I assume it's the identity/type aspect of
an interface you want here which isn't satisfied by that approach.

Also worth noting, although I can't say I'm familiar with the mechanics of
traits in PHP's implementation, my understanding has always been that
they're effectively compiler-level copy and paste in to a class so I'm not
sure what interfaces are implemented by the class (or conversely allowing a
trait to implement an interface) would be readily achievable.

That's my two cents, good luck with whatever you're trying to do anyway.

- David


> --
> Kirill Nesmeyanov


Re: [PHP-DEV] [VOTE] User Defined Operator Overloads

2022-01-03 Thread David Gebler
On Mon, Jan 3, 2022 at 5:38 PM Nikita Popov  wrote:

> On Mon, Jan 3, 2022 at 1:14 AM Jordan LeDoux 
> wrote:
>
> > Hello internals,
> >
> > I've opened voting on
> > https://wiki.php.net/rfc/user_defined_operator_overloads. The voting
> will
> > close on 2022-01-17.
> >
> > To review past discussions on this RFC and the feature in general, please
> > refer to:
> >
> > - https://externals.io/message/116611 | Current RFC discussion
> > - https://externals.io/message/115764 | Initial RFC discussion
> > - https://externals.io/message/115648 | Pre-RFC discussion and
> > fact-finding
> >
> > Jordan
> >
>
> Voted No on this one. I did support the previous proposal on this topic,
> but I don't like the changes that this iteration has introduced relative to
> the previous proposal.
>
> The part that I dislike most (and that I consider an exclusion criterion
> regardless of any other merits of the proposal) is the introduction of a
> new "operator +" style syntax. I found the motivation for this choice given
> in the RFC rather weak -- it seems to be a very speculative
> forward-compatibility argument, and I'm not sure it holds water even if we
> accept the premise.

There's nothing preventing us, from a technical
> point-of-view, from allowing the use of some keyword only with magic
> methods. On the other hand, the cost of this move is immediate: All tooling
> will have to deal with a new, special kind of method declaration.
>

I agree wholeheartedly with this. I don't have a vote but if I did I'd vote
no. I think if operator overloading is to be introduced, new magic methods
using names like __add and __equals are preferable for a number of reasons.


>
> I'm also not a fan of the OperandPosition approach, though I could probably
> live with it. The previous approach using static methods seemed more
> natural to me, especially when it comes to operators that do not typically
> commute (e.g. subtraction).
>
> Regards,
> Nikita
>


Re: [PHP-DEV] header() allows arbitrary status codes

2021-12-22 Thread David Gebler
On Tue, Dec 21, 2021 at 6:59 PM Christoph M. Becker 
wrote:

> Hi all,
>
> a while ago it has been reported[1] that our header() function actually
> allows arbitrary status codes, which may even overflow.  Of course, that
> makes no sense, since the status code is supposed to be a three digit
> code.  So this ticket has been followed up by a pull request[2], and
> Jakub suggested to further restrict the status code to be in range 100 -
> 599.
>

Personally, I don't like restricting the status code to a number in the
100-599 range. As far as I know, RFC 7230 doesn't mandate anything beyond
the requirement of 3 digits and while 7231 may only specify semantics for
1xx-5xx, that doesn't mean there isn't a legitimate use-case in custom or
internal applications for status codes outside the usual semantics.

The overflow part is a legit bug which can and should be fixed, but I'd at
least question whether a user should be obliged to stick to conventional
HTTP semantics via the header() function, or even a strictly conformant
implementation of the standards defined 7320. Maybe this behaviour could be
default but overridable via a new, fourth optional parameter or something,
I don't know...but I can easily imagine someone having a legitimate context
in which they want to send status codes outside the usual range
representing custom semantics.


>
> Since this could break some pathological cases, I wanted to ask whether
> anybody objects to this change for the master branch (i.e. PHP 8.2).
>
> [1] 
> [2] 
>
> Christoph
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Allow null as standalone type

2021-10-05 Thread David Gebler
On Tue, Oct 5, 2021 at 3:45 PM Nikita Popov  wrote:

> On Tue, Oct 5, 2021 at 4:08 PM Côme Chilliet  wrote:
>
> > Le lundi 4 octobre 2021, 10:09:12 CEST Nikita Popov a écrit :
> > > If we make this change, I would however suggest to also support "false"
> > as
> > > a standalone type. I think this change primarily has benefits from a
> > > typesystem completeness perspective rather than a strong practical
> need.
> > > From that angle, it would be nice if all types that are usable in a
> union
> > > are also usable as standalone types, rather than shifting the special
> > case
> > > from null to false.
> >
> > It feels weird/wrong to slowly add values in the type system like this,
> > rather than directly supporting static values as type hints.
> >
> > Why would function a(): null|false {} be legal but function b(): null|0
> > would not?
> >
> > This is inconsistent to me. And adding null, then false, then true for
> the
> > sake of completeness feels like avoiding to treat the static value as
> type
> > hint subject.
> >
>
> Both null and false are already part of the type system. They're not being
> added, neither by the RFC in question, nor by my quoted suggestion. This
> discussion is only about relaxing restrictions on standalone types.
>

I always thought false was part of the type system just to accommodate the
legacy of internal functions which can return a (non-boolean) value or
false. I mean, I've never written code that's type hinted something|false
as a return type, to me a function/method return should either be type
hinted bool or not. Even with union types, if I was writing something|bool
there might be conceivable occasions it's justified, but I'd at least be
asking myself if it could be a design smell in whatever I'm building. I
guess I'm saying I've always considered the fact you *can* do this with
false more a legacy of necessity than a feature which should be built on.
Null is distinctly a type as well as a value so I can see the justification
for the RFC; it seems harder to make that argument for false, beyond saying
"well in PHP, it just is"...but...is that a good thing?


>
> So to answer your question: "null|false" would be legal because
> "string|false" already is. "null|0" would be illegal because there is no
> such thing as a "0" type (in our current type system).


> Regards,
> Nikita
>


Re: [PHP-DEV] json_encode indent parameter

2021-06-02 Thread David Gebler
On Wed, 2 Jun 2021, 23:03 Timon de Groot,  wrote:

> It's not possible to tell json_encode what indentation level should be
> used when using
> the JSON_PRETTY_PRINT option (2, 4, 8, etc). When generating JSON files
> which can be
> used/read/edited by users, indentation starts to become a relevant topic.
>
> - JavaScript has a function called JSON.stringify wich accepts the
> optional 'space' parameter
>- See
>
> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
>
> - Python has a function called json.dump which accepts the optional
> 'indent' parameter
>(which also controls pretty printing)
>- See https://docs.python.org/3/library/json.html#basic-usage
>
> I would like to create an RFC draft to implement an 'indent' parameter.
> Before I start a draft, I need to know if this is a good idea, so I
> start with a few questions.
>
> 1. What do you think of adding an 'indent' parameter?
>

I'm not at all opposed in principle. As you've pointed out, there is both a
use case and precedent in other common languages.

2. How would that parameter work when the JSON_PRETTY_PRINT option is
> not passed?
>

Give it a default value equivalent to whatever JSON_PRETTY_PRINT spits out
at the moment and silently ignore it if not formatting?

3. What do you think of adding json_encode options instead, like
>JSON_PRETTY_PRINT_INDENT_2 and JSON_PRETTY_PRINT_INDENT_4?
>

Personally I'd avoid more magic constants. The argument in favour of this
approach I suppose would be a) there are in practice a very small number of
common values for indentation which tend to be used, 2 and 4 being the most
common and b) there is already a third, optional depth parameter which
would remain before any fourth spacing parameter.

I would say though (a) is true enough but doesn't necessarily cover all use
cases, adds more magic constants and doesn't provide equivalence to the
JSON libraries of other common languages which permit for custom values,
while (b) is less of an issue with PHP 8's named parameters.

So if you do go ahead and make an RFC for this, I think my preference would
be as a new parameter on json_encode accepting a positive integer.


> Looking forward to you replies and feedback!
>
> --
>
> Kind regards,
>
> Timon de Groot
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Consensus Gathering: is_initialized

2021-05-26 Thread David Gebler
On Wed, May 26, 2021 at 11:14 AM Joe Watkins  wrote:

> Hi internals,
>
> In response to: https://bugs.php.net/bug.php?id=78480
>
> I implemented: https://github.com/php/php-src/pull/7029
>
> Not absolutely convinced that it's a good idea, I asked Nikita to review,
> and he's unconvinced also and suggested a discussion should be started.
>
>
I would just like to second (or third, or fourth) the notion that the very
possibility of accessing uninitialized state is a bug in the user's code,
not a problem for which the language should provide a workaround. If a
property is required (i.e. not nullable) it should absolutely and always be
initialized in the constructor.

I do appreciate PHP being how it is, there might be "valid" use cases for
is_initialized() but I also think it will encourage bad practice.

Regards
Dave


Re: [PHP-DEV] [RFC] First-class callable syntax

2021-05-20 Thread David Gebler
On Thu, May 20, 2021 at 8:38 PM Larry Garfield 
wrote:

>
> There's been a lot of rapid iteration, experimentation, and rejection.
> The most recent alternatives are this one from Levi:
>
> https://gist.github.com/morrisonlevi/f7cf949c02f5b9653048e9c52dd3cbfd
>
> And this one from me:
>
> https://gist.github.com/Crell/ead27e7319e41ba98b166aba89fcd7e8
>
>
Intuitively, I think I prefer your algorithm as these are written up.
Levi's allows for named placeholders which I'm sure for some users is a big
draw. But I think what you're proposing is cleaner and will be better
understood. It resolves a lot of the concerns which came up in the PFA
thread, striking a reasonable balance between benefit and simplicity.

Either way suggests compatibility with Nikita's proposal, assuming use of
the spread operator as the implemented syntax. For this RFC in isolation,
though, it does loosely concern me as a user the proposed syntax looks more
like a function call. I won't bog anyone down arguing the syntax, it's a
minor detail for users to get used to in the grand scheme of things and I'd
definitely rather it was possible to build the more powerful PFA on top
than bin that off, or end up with a convoluted PHP providing competing ways
of doing the same thing.


> * Named arguments make things more complicated.  One of the questions is
> whether named placeholders should be supported or not.  And if they are,
> does that mean you can effectively reorder the arguments in the partial
> application, and what does that mean for usability.  It gets complicated
> and scope-creepy fast.
>

I do share the concern about named arguments and it's one of the reasons I
prefer your proposal. I think scaling back the scope a little bit is
exactly what's needed right now.


> While I agree Nikita's RFC here would be an improvement over 8.0, I don't
> think throwing in the towel on PFA yet is a good idea.  It's a much more
> robust and powerful approach that still gets us the "first class callable"
> syntax we all want (at least I assume we all do), and lots of additional
> power to boot.  I'd rather see us try to drive PFA home to completion.  If
> that proves impossible by early July, then this RFC would still get us
> something this cycle, as long as the syntax is still compatible with PFA.
>

I think this is very sensible, I can only really say I'd rather have
Nikita's proposal land in 8.1 and PFAs in 9.0 done right than have PFAs in
8.1 but in a way which is confusing, ambiguous or problematic for users, or
not covering reasonable expected use cases.


Re: [PHP-DEV] [RFC] Partial function application

2021-05-18 Thread David Gebler
On Tue, May 18, 2021 at 11:02 PM Levi Morrison 
wrote:

> Some of the RFC authors have been discussing this a lot based on
> feedback. In a [previous message][1] I said we would message the list
> when it's ready for re-review. It's still not ready, but we seem to be
> driving towards consensus.
>

Okay, great. I thought your previous message only referenced named
placeholders, I didn't take from that you were also considering other
discussion points. Look forward to seeing the updated RFC; personally I
think the meat of it is a good addition to the language, all the sweeter if
it's able to land for 8.1.


Re: [PHP-DEV] [RFC] Partial function application

2021-05-18 Thread David Gebler
On Tue, May 18, 2021 at 9:51 PM Rowan Tommins 
wrote:

> Hi David,
>
> Did you see my message yesterday about the two mental models of the
> feature? https://externals.io/message/114157#114492
>
> Your expectation there is in line with the "start with an empty closure
> and add things" model; the behaviour proposed in the RFC is in line with
> the "copy the full signature and then splice in fixed values" model.
>

Well this is the crux of the issue for me, yes; I think the latter model is
arguably more useful, I think the former model is what the proposed syntax
implies and the former model is therefore the more natural and "readable"
interpretation of what users might expect partials to mean when we're
looking at hypothetical userland code built on this feature. I can't help
but question the value of introducing something which has the potential to
be ambiguous and misinterpreted - and I think the discussion in this thread
has highlighted that there *is* ambiguity.

Further, the RFC as it stands seems to introduce the possibility of writing
ambiguous code when defining a partial. My intuition is that most PHP users
would expect a single placeholder character (?) to represent one and
exactly one parameter, analogous to SQL. But there are other ways you might
reasonably interpret and argue for the syntax, which I think have been
well-expressed by Larry and others.

I don't know what the answer is here, I'm reading through the entire thread
and RFC again and trying to better formulate in my mind how I'd [like to]
reason about this in terms of syntax. But the more I think about it, the
more I realise much as I loved the idea when I first read the RFC, now I'm
worried we're rushing to include something (because there's an
implementation, more or less ready to go) which maybe should go back to the
drawing board for a bit of a re-think.

Maybe I'm wrong, I don't know, but yeah...I have reservations now. If I had
a vote and voting was open at this point, I think my inclination would be
to -1 the RFC as it currently stands, not because it isn't a good idea but
because right now, it will definitely confuse some significant proportion
of users.


>
> I do worry that users of the language will assume the "wrong" mental
> model, though, unless we pick a syntax that more clearly matches the
> "copy and splice" model. I think that would mean having a way to say
> "make this is a partial", and a way to indicate which arguments to
> "splice", without any "placeholders".
>
> Yet Another Bad Unsolicited Syntax Suggestion:
>
> $partial = partial foo(); // no bindings; current RFC $partial = foo(?);
> $partial = partial foo(b: 10); // bind named parameter $b; current RFC
> $partial = foo(?, b: 10);
> $partial = partial foo(1: 10); // bind positional parameter #1
> (zero-indexed); current RFC $partial = foo(?, 10);
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Partial function application

2021-05-18 Thread David Gebler
On Tue, May 18, 2021 at 2:45 PM Larry Garfield 
wrote:

> User-space functions have always accepted more arguments than they're
> defined with.  They just get dropped off the end silently, unless you use
> func_get_args() or variadics.  While I know not everyone likes that
> "feature", it means that extra trailing ? "arguments" don't feel weird to
> me.  They just get dropped off the end and we move on with life.  At least
> that's how I conceptualize them.
>

This is my question about the partials feature, though; does the
implementation have potential to reasonably be confusing? if it's
essentially a convenient way of creating a closure, why would extra
arguments passed in the closure call be passed to the wrapped function,
rather than discarded?

function foo(int $a, int $b, int ...$p) { ... }
$partial = foo(?, 10);

$partial(5, 15, 25);

Intuitively, because the existing convention is extra unused parameters in
user defined functions are silently ignored, I think I would expect the
above to be equivalent to something like:

$partial = fn(int $a) => foo($a, 10);
$partial(5, 15, 25); // 15 and 25 are lopped off to no effect

and not

$partial = fn(int $a, int ...$params) => foo($a, 10, $params);

But correct me if I'm wrong, isn't the latter what the RFC effectively
proposes?


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


Re: [PHP-DEV] Disable interactive mode (-a) if readline not available

2021-05-12 Thread David Gebler
On Wed, 12 May 2021, 09:13 Nikita Popov,  wrote:

>
> I think we would be better off disabling -a completely if readline is not
> available, and exit with a helpful error message. I've opened
> https://github.com/php/php-src/pull/6976 to that effect. Does that sound
> reasonable?
>
> Regards,
> Nikita
>

+1 for this, the shell is very useful but "interactive mode", the evidence
is clear has a tendency to confuse people.
To invert the question, would anyone have a good justification to NOT
remove interactive mode?

>


Re: [PHP-DEV] [RFC] Partial function application

2021-05-11 Thread David Gebler
On Tue, May 11, 2021 at 4:39 PM Larry Garfield 
wrote:

> It looks like the conversation has died down, and it's been two weeks, so
> pending any other notable feedback I'll open a vote on this RFC on Thursday
> or Friday.
>
> --Larry Garfield
>
>
>
 My only query / point of consideration is a very minor one for what is
otherwise an enthusiastic (non-voting) +1. In relation to one of the
examples:

function whole($one, $two) { /* ... */ }
// equivalent to calling whole(1, 2, 3)
$result = whole(?, 2)(1, 3);

Is there a risk this has the potential to be confusing? We've always had
this quirk in PHP of being able to pass extra unspecified parameters in
function calls, but with the exception of variadic functions the
expectation is that they are ignored. Arguably if I saw this:

function whole($one, $two) { /* ... */ }
$partial = whole(?, 2);
$result = partial(1, 3);

I might expect it to semantically translate to:

function partial($one) { return whole($one, 2); }

with the extra parameter, 3, ignored as per convention for any other
function receiving undefined extra params. But the RFC says this parameter
would be passed to whole(). Which is not unreasonable, but yeah I guess it
strikes me it's kind of a quirk in itself to do it that way.

-Dave


Re: [PHP-DEV] PR for minor bugfix in compact()

2021-05-07 Thread David Gebler
Great, that's been updated, build in progress (relevant tests passing
locally). I'd have preferred TypeError but appreciate there being a
consistent convention to follow. These kind of small fixes are also about
me becoming more familiar with typical conventions in the engine - some of
this stuff is just not stuff you'd find out until you stick up a PR and get
feedback from more experienced contributors so it's all good to know.

Dave

On Sat, May 8, 2021 at 12:13 AM Ben Ramsey  wrote:

> Christian Schneider wrote on 5/7/21 02:06:
> > I agree with George that it should be an E_WARNING first and then
> changed to a TypeError in PHP 9.
> > This should be the default process for reasons given in many other
> threads about tightening type rules IMHO.
> >
> > So no, I'd prefer if this PR to be changed to E_WARNING before merging
> it.
> >
> > - Chris
> >
>
> Not a lot of chatter about this on the list, but I also agree that this
> should be an E_WARNING in 8.1 and promoted to a TypeError in PHP 9. This
> is our standard process.
>
> David, please update the PR, and we'll get it merged.
>
> Cheers,
> Ben
>
>


Re: [PHP-DEV] PR for minor bugfix in compact()

2021-04-28 Thread David Gebler
Ah I see, thanks for the clarification! I only did it this way because when
I did my RFC for fsync, I recall one or two people mentioned they weren't
keen on the bit where it could raise a warning rather than a TypeError -
but I appreciate that one was a completely new function and not a change to
an existing one (and it went through with the warning condition in the end,
anyway).

On Wed, 28 Apr 2021, 12:18 G. P. B.,  wrote:

> On Wed, 28 Apr 2021 at 12:12, David Gebler  wrote:
>
>> Hi internals,
>> I've opened a PR to cause compact() to throw a TypeError if its parameters
>> are not valid, which I consider to be a fix for what is effectively a bug
>> whereby logical errors in user code can be silently swallowed.
>>
>> GPB has done an initial review and left a comment
>> https://github.com/php/php-src/pull/6921#pullrequestreview-646848902 in
>> which he suggests I open this up to the floor, so here it is, seeking
>> your feedback kindly. Also if anyone can clarify what is meant by a
>> warning
>> "will be promoted in PHP 9", I am not familiar with what changes are
>> planned for the next major version?
>>
>> Regards
>> David
>>
>
> Hey David,
>
> What I meant is that we usually don't introduce an exception without prior
> warning to existing functionality.
> So making this a Warning in the PHP 8 series which gets promoted to a
> TypeError in PHP 9,
> similarly to how most of the internal functions went from returning null +
> warning to throwing a TypeError,
> or many of the warnings that got promoted to ValueErrors in 8.0 because
> it's a major release.
>
> Personally I don't mind introducing the TypeError immediately in PHP 8.1,
> because compact() should be rather rare
> and mostly used on an array, but others might feel differently about this.
>
> Best regards,
>
> George P. Banyard
>


[PHP-DEV] PR for minor bugfix in compact()

2021-04-28 Thread David Gebler
Hi internals,
I've opened a PR to cause compact() to throw a TypeError if its parameters
are not valid, which I consider to be a fix for what is effectively a bug
whereby logical errors in user code can be silently swallowed.

GPB has done an initial review and left a comment
https://github.com/php/php-src/pull/6921#pullrequestreview-646848902 in
which he suggests I open this up to the floor, so here it is, seeking
your feedback kindly. Also if anyone can clarify what is meant by a warning
"will be promoted in PHP 9", I am not familiar with what changes are
planned for the next major version?

Regards
David


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread David Gebler
Okay, I promise  I'll make this my last word on the thread, for the sake of
my own sanity and at this point, I'm sure that of others - first, I really
appreciate your explanation there for why you consider this RFC a good
thing, so thank you for that. Personally, my objections still stand for in
essence the same reasons as before;

1. In respect of data modelling, you may think you've understood a model
such that its sum is closed, this may even be true for your use case (and
yes, agree both that this is useful and some other languages have better
ways of expressing it) but sometimes, it is only true until it isn't. E.g.
you have said colours are red, green and blue. This is fine until someone
else needs to reason about purple and can't because your data model says
there is no purple.

2. A (non-functional) attribute [or other syntax/convention] for sealed
does not / should not be interpreted as saying "pretty please, don't extend
me", it says "I don't endorse/support this, but if I haven't accounted for
your use case and you're confident you understand your problem, hey, don't
let me stand in your way" - other interpreted languages (Python comes to
mind) use this approach very effectively and their ecosystems are not
automatically riddled with bad models as a result. Indeed PHP is in some
respects unusually strict for an interpreted language (though I am not
saying that is necessarily a bad thing).

3. That there are valid use cases for a language construct does not mean
people will only use it for those cases - I'd go as far as to say they
definitely won't. Annotation in some form is safe in all use cases, fatal
errors aren't. So I stand by the real, primary benefit of these constructs
- delineation of intent boundaries - is achieved without creating a
construct which introduces a new fatal error condition.

Anyway, yeah - I've said my piece(s) and I'm not a voting member so what I
think doesn't matter to that end. I hope my input on internals discussions
is not entirely moot, though; just like everyone else I take part because
I'm very fond of PHP and have an interest in its future. Appreciate those
who are willing to hear me out.

On Wed, Apr 28, 2021 at 12:00 AM Larry Garfield 
wrote:

> On Tue, Apr 27, 2021, at 5:48 PM, David Gebler wrote:
> > On Tue, Apr 27, 2021 at 11:23 PM Larry Garfield 
> > wrote:
> >
> > The two options to prevent such errors are:
> > >
> > > 1. Sealed classes.
> > > 2. Extend Enums into ADTs.
> > >
> >
> > Unless I've misunderstood your example, there is a third option which
> quite
> > possibly prevents the error in a nicer, easier to reason about, more
> > flexible pattern.
> >
> > class Perhaps extends Maybe implements OperatesOnTheValueInterface { ...
> }
>
> If we were dealing with a service object in classic OOP (viz, OOP based on
> classes), then yes, turning the function into a method and using
> polymorphism would be the correct answer, rather than RTTI.
>
> However!  Classic OOP design patterns are not all that PHP supports, and
> that's a good thing.  The "class" construct, for better or worse, is the
> syntax for logic objects, value objects, data objects, and control flow
> objects (such as Maybe, Either, etc.), plus assorted other patterns that
> are not part of the classic OOP canon.  But they're still good and useful
> patterns, and often a better model than classic OOP "polymorph all the
> things" approaches.
>
> If we were designing PHP from scratch today, I'd argue for having separate
> language constructs for funcy-syntax-closures (which is what service
> objects are), product types (structs, value objects, all the same thing),
> and control flow types.  Many newer languages do differentiate those
> better.  That's not where we are, though, so we're stuck with class being
> the uber-syntax for anything even slightly interesting from a type
> perspective.  So be it, but it does lead to ample confusion about which use
> case you're talking about, especially when not everyone is familiar with
> all of the different, distinct use cases.
>
> See also: This thread. :-)
>
> Sealed classes are... not really useful at all for service object use
> cases.  They are useful for product type and control flow type use cases.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread David Gebler
On Tue, Apr 27, 2021 at 11:23 PM Larry Garfield 
wrote:

The two options to prevent such errors are:
>
> 1. Sealed classes.
> 2. Extend Enums into ADTs.
>

Unless I've misunderstood your example, there is a third option which quite
possibly prevents the error in a nicer, easier to reason about, more
flexible pattern.

class Perhaps extends Maybe implements OperatesOnTheValueInterface { ... }


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread David Gebler
On Tue, Apr 27, 2021 at 6:56 PM Levi Morrison 
wrote:

> I think the conversation on final classes being "bad" has gone on long
> enough. You don't like final, and you don't want to see more features
> like it being added, such as sealed. Point taken. Now please stop
> dominating the discussion, thank you.
>

In a thread of around 50 messages, I have posted six of them, half of which
are addressing direct replies to the other half. I have also not treated
anyone rudely, disrespectfully, or  gone off-topic. That is not dominating,
it is healthy discussion which should be encouraged. If you don't want to
read my contributions, I'm sure you can filter them.

Nonetheless, you may be pleased to know as far as I'm concerned, I have
fully expressed my view and reasoning on this RFC and have nothing further
I wish to add to the conversation.


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread David Gebler
On Tue, Apr 27, 2021 at 6:19 PM Pierre  wrote:

> Le 27/04/2021 à 18:46, David Gebler a écrit :
> > What's being proposed in the RFC is a functional change to the language
> > whereby attempting to extend a class designated as sealed to a
> > non-specified child results in a fatal error.
>
> It's not a functional change to the language, well, it is a new feature,
> but it's actually not changing any paradigm in the language or the
> engine. People will continue to write the same code, and people that
> want to use it for some library or customer project internal purpose may
> use it.
>

If you introduce it, people will use it and the people who use their code
will (no pun intended) inherit it. So the idea that no one is obligated to
use this pattern if they don't want to is at least de facto untrue.


>
> > Now that is not a benefit in itself, it is merely a description of the
> > proposed change. My question is who or what benefits from this change?
> And
> > I look at this way:
> >
> > 1. The language engine doesn't benefit, since unlike some compiled
> > languages, there is no indication here it will result in improved opcode
> > sequences.
> >
> > 2. The author of code doesn't benefit, to any extent greater than they
> > would by using an attribute or other metadata to indicate their
> intentions,
> > because if someone else comes along, installs their library and creates
> > problems for themselves by extending some concrete type in a manner which
> > was not intended, the author's obligation to them is zero. If improperly
> > inheriting or otherwise misusing code creates a problem for a consumer,
> > it's the consumer's mess to sort out.
>
> I think that the debate "but if your seal your classes I won't be to
> extend it" is overrated: it's not the language to chose whether or not
> the library/software author can seal its classes or not, it's up the
> library/software author to do its own choice.


Agree, which is precisely why I challenge there is any need for it to be
enforced in the language with a fatal error.


> And in that regard, having
> "sealed" classes in the language is actually bringing that possibility
> to the library author, so it's more liberty.
>
> By design, by convention, in any of a company or an open source software
> community, it can be legit to explicitly hard-seal stuff, for blocking
> users when they are doing it wrong, if for example by attempting to
> inherit they will break other existing piece code, for example. There's
> many scenarios where it's legit to seal classes, and it can be a good
> practice also (depend on your practices I guess).
>
> But if sealing means "you who want to change a behavior, you need to fix
> other things deep in the code before being able to do that" then it's
> good (and it's one of the use cases of sealing).
>
> So each time someone use the "but we won't be able to legitimately
> extend your class" he's basically saying that people that do put very
> thorough and strict conventions in their own code are wrong by nature
> and don't understand what is good. It's almost an insult - please don't
> misunderstand what I say,


I entirely understand and appreciate your view here, but it's no more
insulting than to say to your users "You are wrong by nature; I know your
use-case better than you do (without even seeing it or having knowledge of
it) and there is no legitimate reason for you to ever extend my class"


> I don't think at any moment that any of the
> people here really meant that, but it it's fundamentally what this
> argument does: it says that some conventions are by nature bad and the
> language should enforce people not to write code like this.

I think the language should not enforce any practice, convention or code
> style, it must remain neutral considering people's whereabouts,
> workflows or practices. If one's want to seal his or her class, let him
> or her do it.
>

Some conventions may or may not be bad by nature but that's not the
argument I'm making, at all. The language enforcing one person's
preferences over another's is exactly what you are advocating and I am
cautioning against.


>
> I think this point/argument should be banned from this discussion.


Given the behaviour we're talking about is literally the change proposed in
the RFC, I find this a very strange take.


>
> Sealed classes are good under some conditions, maybe bad under others,
> that's not the point, it's not about discussing each developer's,
> community's or company's own conventions, but about is it OK technically
> to add this feature to the language, and will it be or not a maintenance
> burden, and finally will it actually brea

Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread David Gebler
Still, it remains that one could have a legitimate, justifiable reason to
extend Maybe / some other example, which was not foreseen by its author and
is prevented by sealed as a keyword despite the fact this inheritance,
correctly implemented, would not break anything, not define an impossible
state and not violate anything except the library author's own (limited)
imagination of how their code ought to be used.

Note in respect of the point people have raised about attributes and my own
previous comments, I am not advocating any Sealed attribute is added to the
language as a functional change or embedded language by the backdoor, I am
merely saying *you* as some class's author can add an attribute, right now,
to indicate that you consider the class sealed - and an IDE / automated
tooling could understand it and warn a user there is a risk to violating
it.

What's being proposed in the RFC is a functional change to the language
whereby attempting to extend a class designated as sealed to a
non-specified child results in a fatal error.

Now that is not a benefit in itself, it is merely a description of the
proposed change. My question is who or what benefits from this change? And
I look at this way:

1. The language engine doesn't benefit, since unlike some compiled
languages, there is no indication here it will result in improved opcode
sequences.

2. The author of code doesn't benefit, to any extent greater than they
would by using an attribute or other metadata to indicate their intentions,
because if someone else comes along, installs their library and creates
problems for themselves by extending some concrete type in a manner which
was not intended, the author's obligation to them is zero. If improperly
inheriting or otherwise misusing code creates a problem for a consumer,
it's the consumer's mess to sort out.

3. The consumer of code doesn't benefit, because if they didn't intend to
inherit from a sealed, concrete class, it being sealed makes no difference.
But if they did - and had a legitimate reason to do so - they are now
forced to fork, proxy or otherwise work around this artificial restriction
(which they can easily do, by the way, language keyword or none). In any
valid use case, this can distinctly and only be a disadvantage to them.

Someone - Larry I think - said something to the effect of this isn't about
restricting your users as an author from doing something you think they
shouldn't, and that it's about more completely defining problem spaces at
language level. I respectfully am not convinced. When we look at features
like enums and stronger typing, we can see distinct benefits in how as
users of PHP we can model better and write better, more effective and more
efficient code.

But in the case of sealed and the context of PHP, you cannot model your
problem space this way better than you can with an attribute or other means
of annotating metadata. I can certainly agree such metadata is an important
part and valuable tool for improved modeling, but making it a keyword and
throwing a fatal error if your limited intentions (which do not predict all
possible use cases) are violated is merely constraining users from being
able to do something for its own sake. While there is a legitimate argument
that serves to "syntactically make certain invalid states impossible", it
does the same for any valid states you didn't envision.

I'm maybe even inclined to suggest the desire to make a class sealed really
smells like you want to be using abstract classes and/or interfaces.

To the greatest extent which is practical, my preference is to enable other
developers rather than constrain them (subject to the caveat I will not
help them if they do something silly or irresponsible with my code on their
own volition) - I don't believe the "weirdness" exceptions PHP makes
internally for things like Throwable or Traversable are good reasons to
extend this to the language level.



On Tue, 27 Apr 2021, 16:05 Guilliam Xavier, 
wrote:

> Hi,
>
> On Mon, Apr 26, 2021 at 9:54 AM Christian Schneider  >
> wrote:
>
> > Am 25.04.2021 um 05:47 schrieb Larry Garfield :
> > ...
> > > sealed class Maybe permits Some, None {
> > ...
> > > }
> > >
> > > final class None extends Maybe {}
> >
> > This is exactly the thing I'm worried about.
> >
> > Say I want to add something like logging to the None type.
> > Now your sealed and final classes prevent me from defining MyNone
> > extending None even though it would be 100% compatible with None.
> >
>
> I just want to note that this has nothing to do with Maybe made sealed
> (which seems legit), only with None made final (which... could be debated,
> but unrelated to the RFC at hand).
>
> Regards,
>
> --
> Guilliam Xavier
>


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-26 Thread David Gebler
Yes I agree Chris, this is the same kind of argument I am making.

> Note that the *exact* same argument could be made for typing parameters.
I can document via a docblock that I expect a given parameter to be a
string, or a Request object, or whatever.  "There is little to no benefit
in expressing that through a new language construct rather than through
existing constructs and design patterns."

Yes and no. There is a critical difference between type checking and sealed
- type checking can actually prevent and catch bugs in the form of
objective logical errors (e.g. $total = getSum(1, 2, "not a number"))
before they occur, whereas sealed can only prevent things you did not
intend or foresee, without knowing anything about how I am using some code;
there is no bug or logical error which the use of sealed will prevent *in
and of itself*.

> Except there very much is a benefit, for making the intent of code
clearer and for allowing the engine to syntactically make certain invalid
states impossible.

This is not runtime benefit, it is runtime overhead. PHP cannot generate a
better opcode sequence for knowing a class is sealed. In terms of
implementation, the only thing it can do is scream "Hey! The author of this
class didn't intend for you to use it this way!" - your IDE can do that
from an attribute.

And although I would say the claim no one will ever have a legitimate &
good reason to extend some class and be able to do so in a way which does
not violate whatever protections against invalid state you had in mind is a
very bold prediction which is rarely borne out by reality - my objection
here is not about people marking classes as sealed, it's that we don't need
a new language construct and keyword to achieve the only benefit it
delivers (declaration of intent to users and IDE). If PHP reasoned about
classes in the same way compiled, statically typed languages do and
therefore derived some tangible compile-time benefit from a sealed
construct, I would be in favour of it.


On Mon, 26 Apr 2021, 08:54 Christian Schneider, 
wrote:

> Am 25.04.2021 um 05:47 schrieb Larry Garfield :
> > In practice, I think all of the use cases for sealed classes are
> ADT-esque.  As I noted before, combining sealed classes with Nikita's
> new-in-expressions RFC would allow for this (also using my short-functions
> RFC for this example, although that's a nice-to-have):
> >
> > sealed class Maybe permits Some, None {
>
> ...
>
> > }
> >
> > final class None extends Maybe {}
>
>
>
> This is exactly the thing I'm worried about.
>
> Say I want to add something like logging to the None type.
> Now your sealed and final classes prevent me from defining MyNone
> extending None even though it would be 100% compatible with None. Just
> because *you* deemed that useless or wrong.
>
> I've encountered situations like this and came to the conclusion that
> while this makes sense for languages like Haskell - where the whole idea is
> to be able to reason about a complex type system - it is an anti-pattern
> for other languages like PHP.
>
> Referring to another post, not yours: People, please don't use Java as a
> reason to add something to PHP, Java is the king of anti-patterns ;-)
>
> - Chris
>
>


Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread David Gebler
On Sun, Apr 25, 2021 at 8:52 PM Mike Schinkel  wrote:

> > On Apr 25, 2021, at 1:52 PM, David Gebler  wrote:
> >
> > Still, all these problems are solved to the same degree if you add a
> > #[Sealed] attribute to a class which has no functional impact. You have
> > sufficiently indicated to any user that extending this class is not a
> > designed feature and may cause backwards-incompatible breaks with future
> > releases - in a way that both a programmer and IDE can reason about,
> which
> > in PHP's context is what matters. Attributes arguably even have a greater
> > qualitative advantage that they can be applied right down as far as
> > individual method parameters.
>
> In my experience, if a developer needs access to a feature that is easily
> available via the use of a method that is merely documented as internal-use
> only, the developer will use it rather anyway than spend a lot more time
> trying to work around what that method makes easily available.  Especially
> if that documented internal-use only is about not subclassing.
>
> And if many other developers do that, the original developer will still
> have the same problem as if they didn't document it as internal-use only.
>
> But I do acknowledge your experience might be different.  FWIW.
>

You're answering a different point to the one I'm making, which is that in
contrast to a language like Java, where the compiler gets a benefit out of
reasoning about virtual vs non-virtual methods, the use of sealed as a
language construct in an interpreted language like PHP can do nothing which
isn't already achieved by annotation - the expression of intent.


>
> > In Java the idea of final and sealed classes makes more sense, since we
> > actually to some extent need the compiler to be able to reason about
> these
> > types and can gain optimization and code generation benefits from its
> being
> > able to do so. PHP's concept of typing and implementation of type
> checking
> > as an interpreted language is completely different.
> >
> > I wonder, if final and sealed as language constructs really offer the
> > guarantees about intent and safety their advocates say they do, why are
> > they not the default? Why can no one point me to a language where I have
> to
> > write something like
> >
> > extendable class Foo permits all {  }
> >
> > (and there are people who would be in favour of making inheritability
> this
> > explicit, but I'm not one of them)
>
> Well, I can't point you to a language that works that way because I don't
> know more than a handful of languages in depth — although there may be one
> — but I can point you to a language that does not even allow you to
> subclass: Go.
>
> The Go designers wanted to get away from the fragile base class problem so
> they provided embedding instead:
>
>
> https://medium.com/@simplyianm/why-gos-structs-are-superior-to-class-based-inheritance-b661ba897c67
>
> I program more in Go now than in PHP, and I can confirm that its approach
> works brilliantly. Better IMO than what PHP currently offers in that
> respect.
>

Again, this doesn't seem relevant to the discussion in respect of PHP or
the RFC we're talking about. I don't have a Go background but I'm learning
it at the moment and I like it a lot. Nonetheless it's neither comparable
to PHP nor object oriented in a conventional sense so any direct comparison
here is probably not too useful.


>
> > It's one thing as an author of code to say "I only intended and support
> > this finite set of use-cases", it's quite another to say "and you should
> be
> > impeded from proceeding with any legitimate use-case I didn't imagine or
> > foresee"
>
> I do respect that as a user of other developer's code you might view it
> that way.
>
> But then I also can respect the library or framework developer who chooses
> to make their own job less difficult by (wanting to) mark a class to be
> sealed.
>
> You claim "it's quite another thing to say" but I don't think a developer
> of library or framework code should be required to offer features to their
> users they do not want to offer.  It is the developer's prerogative; if
> they want to be able to mark their classes as sealed they should be
> empowered to do so. IMHO, anyway.
>

My argument is not that there aren't legitimate cases where you want to
indicate a class or interface as sealed, nor that developers should not be
empowered to make this indication. It is that in PHP, as an interpreted
language, there is little to no benefit in expressing this through a new
language construct than through existing constructs and design patterns.


>

Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread David Gebler
Still, all these problems are solved to the same degree if you add a
#[Sealed] attribute to a class which has no functional impact. You have
sufficiently indicated to any user that extending this class is not a
designed feature and may cause backwards-incompatible breaks with future
releases - in a way that both a programmer and IDE can reason about, which
in PHP's context is what matters. Attributes arguably even have a greater
qualitative advantage that they can be applied right down as far as
individual method parameters.

In Java the idea of final and sealed classes makes more sense, since we
actually to some extent need the compiler to be able to reason about these
types and can gain optimization and code generation benefits from its being
able to do so. PHP's concept of typing and implementation of type checking
as an interpreted language is completely different.

I wonder, if final and sealed as language constructs really offer the
guarantees about intent and safety their advocates say they do, why are
they not the default? Why can no one point me to a language where I have to
write something like

extendable class Foo permits all {  }

(and there are people who would be in favour of making inheritability this
explicit, but I'm not one of them)

It's one thing as an author of code to say "I only intended and support
this finite set of use-cases", it's quite another to say "and you should be
impeded from proceeding with any legitimate use-case I didn't imagine or
foresee"

In practice, the only thing I've ever seen this achieve is to create
difficulties, while the claimed benefits can be adequately (and better)
achieved through existing patterns like annotations, interfaces and DI.


On Sun, Apr 25, 2021 at 4:36 PM Mike Schinkel  wrote:

>
>
> On Apr 24, 2021, at 7:39 PM, David Gebler  wrote:
>
> I don't love this idea, I'm not very fond of the final keyword, either;
>
>
> I'll start by saying the final keyword caused me a tremendous amount of
> heartache because it was used on a class in a framework that I badly, badly
> needed to extend.
>
> But even so, I recognize why they used it, and I still don't have a great
> argument for how they could address the reasons they used it some other way.
>
> I've always believed annotations (or attributes in PHP these days) are a
> better of way of indicating you, as an author of a class, did not write it
> with inheritability in mind or intended than restricting language features
> through syntactic constructs.
>
> The RFC says "when you have a class in your code base that shares some
> implementation detail between 2 or more other objects, your only protection
> against others making use of this class is to add `@internal` annotation,
> which doesn't offer any runtime guarantee that no one is extending this
> object", to which I ask - why do you need this guarantee? What does it
> qualitatively add? If I make a judgement that I want to extend your class
> or implement your interface, I can just delete the sealed keyword from your
> code and carry on. So it doesn't actually offer any guarantee at all that
> I'm not extending the type.
>
>
> Actually, it does offer such a guarantee.  It guarantees if you are using
> a non-forked version of the original developer's (OD's) library or
> framework then that class won't be extended. When someone pulls the
> original non-forked version from its source repository — such as when using
> Composer — then that code will be (effectively) guaranteed not to be
> extended.
>
> OTOH, if you do delete the sealed (or final) keyword you have then forked
> the code, in a defacto manner if not a literal one. If you use a forked
> version of the code, you now own the maintenance of that code and any bugs
> that are generated by your forked changes in using code. The original
> developer has no moral, ethical or even contractual obligation to care
> about the breakage you cause.
>
> Hypothetical example:  You fork the code, remove sealed/final, then
> subclass the code and add a method, let's call it ToString(). And you write
> your application to use ToString(). Now the OD releases a new minor version
> and they also add a ToString() method. Applications using your fork
> probably cannot use the new version of the OD's library because when the
> library calls ToString() your version is called. So you have to update your
> application to use the new version of the library and once again remove
> sealed/final.
>
> AND, if your code is instead another add-on library, now users of your
> add-on library will also have to fix their code too.  Which could
> potentially be a large number of users if your add-on is successful.
>
> So not using final or sealed can result in some really hairy and possibly
> impossible to fully resol

Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-24 Thread David Gebler
I don't love this idea, I'm not very fond of the final keyword, either;
I've always believed annotations (or attributes in PHP these days) are a
better of way of indicating you, as an author of a class, did not write it
with inheritability in mind or intended than restricting language features
through syntactic constructs.

The RFC says "when you have a class in your code base that shares some
implementation detail between 2 or more other objects, your only protection
against others making use of this class is to add `@internal` annotation,
which doesn't offer any runtime guarantee that no one is extending this
object", to which I ask - why do you need this guarantee? What does it
qualitatively add? If I make a judgement that I want to extend your class
or implement your interface, I can just delete the sealed keyword from your
code and carry on. So it doesn't actually offer any guarantee at all that
I'm not extending the type. The best it can achieve is to indicate your
intentions, which I believe can be adequately done today through an
attribute, no addition to the language needed.

On Sat, Apr 24, 2021 at 9:01 PM Christian Schneider 
wrote:

> Am 24.04.2021 um 21:51 schrieb Marco Pivetta :
> > On Sat, Apr 24, 2021, 21:44 Olle Härstedt  > wrote:
> >
> >> 2021-04-24 17:59 GMT+02:00, Saif Eddin Gmati :
>  Doesn't this violate the principle: It should be possible to add new
>  features without touching old code?
> >>>
> >>> This depends on which syntax is picked, both `for` and attribute syntax
> >> will
> >>> be completely BC.
> >>
> >> I'm not talking about BC, but the maintainability of the new feature
> >> itself. For the shape example, you'd need to edit the original file
> >> for each new shape you add, which is detrimental for maintainability
> >> and scalability. So what's a good use-case?
>
> I'm with Olle here: This sounds like an anti-pattern to me.
> The example could not be worse: Why should I not be allowed to add a
> hexagon shape?
>
> > The main use-case of sealed types is being able to declare total
> functions
> > around them.
>
> Could you elaborate on what's the real-world use-case for your main
> use-case?
> This sounds like another case of a feature based in (math) theory which
> leads to artificially locked down code.
>
> - Chris
>
>


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

2021-04-12 Thread David Gebler
Good example of why commit() should throw an exception, I think - it's just
alerted the developer that executing their previous statement has caused an
implicit commit. Imagine if they had a complex sequence of queries and
didn't realise they'd added one which ended the transaction, thinking they
could safely rollback later if necessary. The exception catches this early
on.

Regards,
David Gebler

On Mon, Apr 12, 2021 at 1:07 PM Nikita Popov  wrote:

> Hi internals,
>
> Since PHP 8.0, PDO fully supports MySQL transactions -- this means that
> inTransaction() will report the actual connection transaction state, as
> opposed to an emulated (incorrect) transaction state tracked by PDO itself.
>
> This has two primary effects: PDO is aware of transactions created without
> going through it's APIs (e.g. by manually issuing a START TRANSACTION
> query) and is aware of implicit commits (see
> https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html for more
> information).
>
> The latter means that code like
>
> $pdo->beginTransaction()
> $pdo->exec('DROP TABLE foobar'); // Implicitly commits transaction
> $pdo->exec('DROP TABLE barfoo'); // Transaction not active anymore
> $pdo->commit(); // Throws because no transaction active
>
> now throws an exception, because commit() is called without an active
> transaction. It's possible to use if ($pdo->inTransaction())
> $pdo->commit(); if you don't care about the lack of active transaction.
>
> I believe this behavior is correct, but I could see an argument made in
> favor of always allowing commit() calls (but not rollBack() calls) even if
> there is no active transaction. That would change the meaning of commit()
> from "commit an active transaction" towards "commit if an active
> transaction exists".
>
> Any opinions on that?
>
> Regards,
> Nikita
>


Re: [PHP-DEV] Built-in decorator attribute?

2021-03-15 Thread David Gebler
> Would it make sense to have both options?

If you have the wrapper pattern, you already have both options. This would
be my preferred way of doing it but harder to implement, particularly in
any way which significantly mimics Python's way of doing it.

> One problem with the wrapper pattern is that if you have multiple
decorators then wouldn't that end up calling the function multiple times?
Not so with the before/after.  It really depends on the intended behavior.
How does Python and others handle this?

Python the @decorator syntax is just sugar for re-assigning a method so
they are easily stacked. Say we have a trivial decorator:

def timer(func):
def wrap():
start = time.perf_counter()
func(*args)
end = time.perf_counter()
print("Did thing in this many seconds...")
return wrap

Then

@timer
def foo(a, b, c):
# do some stuff

is equivalent to foo = timer(foo)
and

@timer
@somethingElse
def foo(a, b, c):
# do some stuff

is equivalent to foo = timer(somethingElse(foo))

Regards,
David

On Mon, Mar 15, 2021 at 1:46 AM Peter Stalman  wrote:

> On Sun, Mar 14, 2021 at 6:34 PM Peter Stalman  wrote:
>
>> Would it make sense to have both options?
>>
>
> 6) Multiple decorators on the same function?
> One problem with the wrapper pattern is that if you have multiple
> decorators then wouldn't that end up calling the function multiple times?
> Not so with the before/after.  It really depends on the intended behavior.
> How does Python and others handle this?
>
> Thanks,
> Peter
>
>
>


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

2021-03-14 Thread David Gebler
The information you were given on StackOverflow is somewhat misleading,
since it is referring to the behaviour of PDO::quote(), not anything to do
with binding parameters. The referenced bug report is indeed not a bug.

Still, I don't really use Postgres but a quick smoke test indicates you're
not wrong about the behaviour of bindValue/bindParam on the PG driver when
emulation mode is switched off.

$pdb->exec('CREATE OR REPLACE FUNCTION baz(in int, out f1 text) AS $$
SELECT CAST($1 AS text) || \' as int\' $$ LANGUAGE SQL;');
$pdb->exec('CREATE OR REPLACE FUNCTION baz(in text, out f1 text) AS $$
SELECT $1 || \' as string\' $$ LANGUAGE SQL;');

var_dump( $pdb->query('SELECT baz(23);')->fetchAll() );
 ["baz"]=> string(9) "23 as int"

var_dump( $pdb->query('SELECT baz(\'23\');')->fetchAll() );
["baz"]=>string(12) "23 as string"

$st=$pdb->prepare('SELECT baz(?)'); $st->bindValue(1,3,PDO::PARAM_INT);
$st->execute(); var_dump($st->fetchAll());
["baz"]=>string(11) "3 as string"

Looks like your only option is:
$st=$pdb->prepare('SELECT baz(CAST(? AS int))');
$st->bindValue(1,3,PDO::PARAM_INT); $st->execute();
var_dump($st->fetchAll());
which gives the expected
["baz"]=>string(8) "3 as int"

Whether this is a *bug* I can't really say, there might be a reason
Postgres is implemented this way on PDO, I don't know, I'm not a Postgres
guy.

But the funny thing is it works exactly as expected when emulation is
switched ON:

$pdb->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
$st = $pdb->prepare('SELECT baz(?)'); $st->bindValue(1,3,PDO::PARAM_INT);
$st->execute(); var_dump($st->fetchAll());
  ["baz"]=>string(8) "3 as int"

Regards,
David

On Sun, Mar 14, 2021 at 8:19 PM Benjamin Morel 
wrote:

> 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] Built-in decorator attribute?

2021-03-14 Thread David Gebler
Python's implementation of decorators is great for these kinds of reasons.
You get direct access to the function being called, the arguments which
were passed to it and any return value after (and if) you execute it.
Python's magic here, of course, is that functions and class methods are
first class objects we can reassign at will, so decorators are just
syntactical convenience.

An attributes-based PHP implementation will I think necessarily look and
behave a bit differently, but we should be able to achieve much the same
purposes with before and after hooks. I'm willing to forgo being able to
manipulate the arguments passed to the decorated function before it's
called, but any before hook would at least need to be able to access them
to be useful. Similarly I think you need to be able to get the return value
of the decorated function in an after hook. The Timer is a trivial example
which doesn't need these, but most useful hooks would.

A simple real-world use case example: I have a library which abstracts a
database layer and the Database class is full of public methods which take
a table name parameter. In every single method which does this, right at
the top I have a condition if ($this->isValidTableName($name))

I'd love to be able to replace that with a #[ValidTableName] decorator,
which obviously would need to access the parameter passed to the attributed
function. If I could throw an exception from that decorator, to effectively
prevent the decorated method being called if the table name is not valid
(and this should require no additional implementation in C beyond what
Ben's suggested), overall I think we've got a good basis of a useful
feature.

Equally though, I think this is potentially a really, really useful and
powerful enough feature that it deserves more attention and forethought
before I try to cobble something together as a Frankenstein monster. I'm
starting to familiarize myself with the attributes implementation in the
meantime to try and build up an idea of how I might build this.

Regards,
David


On Sun, Mar 14, 2021 at 4:31 PM Larry Garfield 
wrote:

> On Sun, Mar 14, 2021, at 7:33 AM, David Gebler wrote:
> > Hi Ben,
> > I have been looking at your #[Deprecated] PR to get an idea of where to
> > start with implementing this, I think Peter's suggestion of how it might
> > look syntactically is also interesting - it's exactly that sort of
> question
> > of how would you imagine devs implementing and using decorators in PHP
> that
> > I wanted to get a feel for before I started trying to build it or draft
> an
> > RFC. Your other tips regarding zend_observer and zend_call_function are
> > much appreciated, saves me a lot of digging through the source figuring
> out
> > the appropriate APIs for myself.
> >
> > Before and after hooks are a similar but slightly different
> implementation,
> > semantically, to what I was originally suggesting but may be the
> preferred
> > option. I think to be useful, you probably still need some way to choose
> > not to call the original, decorated function - but I guess you could just
> > throw an exception in your before hook and that might be sufficient
> control
> > in practice.
> >
> > Regards,
> > David
> >
> > On Sun, Mar 14, 2021 at 11:52 AM Benjamin Eberlei 
> > wrote:
> >
> > >
> > >
> > > On Sat, Mar 13, 2021 at 5:51 PM David Gebler 
> > > wrote:
> > >
> > >> With the introduction of attributes in PHP 8, this new behaviour is
> still
> > >> quite sparsely documented. Some of the articles I've seen out there,
> > >> though, liken PHP's attributes to similar constructs in other
> languages
> > >> including decorators in Python.
> > >>
> > >> Attributes are not the same thing as (Python's concept of) decorators
> and
> > >> they shouldn't be confused; a decorator is a function which wraps
> another
> > >> function and is automatically called in place of the wrapped function.
> > >>
> > >> This isn't currently possible in PHP. Using frameworks like Symfony,
> we
> > >> can
> > >> start to build things like this:
> > >>
> > >> class UserProfileController {
> > >> #[LoginRequired]
> > >> public function editProfile(...) { }
> > >> }
> > >>
> > >> but the logic of enforcing our "require the user to be logged in"
> > >> decorator
> > >> relies on the surrounding framework controlling the flow of execution,
> > >> reading the attribute and deciding whether to call the decorated
> method
> > >> editProfile() at a

Re: [PHP-DEV] Built-in decorator attribute?

2021-03-14 Thread David Gebler
Hi Ben,
I have been looking at your #[Deprecated] PR to get an idea of where to
start with implementing this, I think Peter's suggestion of how it might
look syntactically is also interesting - it's exactly that sort of question
of how would you imagine devs implementing and using decorators in PHP that
I wanted to get a feel for before I started trying to build it or draft an
RFC. Your other tips regarding zend_observer and zend_call_function are
much appreciated, saves me a lot of digging through the source figuring out
the appropriate APIs for myself.

Before and after hooks are a similar but slightly different implementation,
semantically, to what I was originally suggesting but may be the preferred
option. I think to be useful, you probably still need some way to choose
not to call the original, decorated function - but I guess you could just
throw an exception in your before hook and that might be sufficient control
in practice.

Regards,
David

On Sun, Mar 14, 2021 at 11:52 AM Benjamin Eberlei 
wrote:

>
>
> On Sat, Mar 13, 2021 at 5:51 PM David Gebler 
> wrote:
>
>> With the introduction of attributes in PHP 8, this new behaviour is still
>> quite sparsely documented. Some of the articles I've seen out there,
>> though, liken PHP's attributes to similar constructs in other languages
>> including decorators in Python.
>>
>> Attributes are not the same thing as (Python's concept of) decorators and
>> they shouldn't be confused; a decorator is a function which wraps another
>> function and is automatically called in place of the wrapped function.
>>
>> This isn't currently possible in PHP. Using frameworks like Symfony, we
>> can
>> start to build things like this:
>>
>> class UserProfileController {
>> #[LoginRequired]
>> public function editProfile(...) { }
>> }
>>
>> but the logic of enforcing our "require the user to be logged in"
>> decorator
>> relies on the surrounding framework controlling the flow of execution,
>> reading the attribute and deciding whether to call the decorated method
>> editProfile() at all.
>>
>> What we *can't* do is something like this:
>>
>> class Foo {
>> private function timer(callable $wrapped)
>> {
>> $start = microtime(true);
>> $wrapped();
>> $end = microtime(true);
>> $total = $end - $start;
>> echo "Executed function in $total second(s)\n";
>> }
>>
>>  #[timer]
>> public function bar($a, $b) { ... }
>>
>> #[timer]
>> public function baz($a, $b) { ... }
>> }
>>
>> What I'm wondering is whether there's a desire / interest for a built-in
>> attribute to provide this kind of behaviour modification.
>>
>> I'm thinking something like
>>
>> class Foo {
>> private function timer(callable $wrapped) { ... }
>>
>> #[Decorator([self::class, 'timer'])]
>> public function bar() {
>> echo "Bar";
>> }
>> }
>>
>> Where this would result in any call to $foo->bar() being equivalent to as
>> if the above were defined as:
>>
>> class Foo {
>> private function timer(callable $wrapped) { ... }
>>
>>  public function __bar() {
>> echo "Bar";
>>  }
>>
>> public function bar() {
>> return $this->timer([$this, '__bar']);
>> }
>> }
>>
>> I'm not saying I have the skills to implement this attribute (though I'd
>> happily try), I'm not even in a position to propose a draft RFC at this
>> stage, just throwing the idea out there to get a feel for what people
>> think
>> of the concept?
>>
>
> In my opinion it would be a fantastic addition to Core to be used by
> application frameworks with "hook philosophies" that hack this
> functionality on top of PHP with code generation or event dispatchers at
> the moment (Magento 2, Drupal, Neos, Wordpress and so on) makes this a
> potential future with wide adoption. If you'd get 2/3 votes for it is
> another topic.
>
> However, as functionality it could be provided as an extension first for a
> proof of concept. The ingredients are all there, it doesn't need to be in
> core:
>
> 1. Register an internal attribute, see my #[Deprecated] PR as an example
> https://github.com/php/php-src/pull/6521
>
> 2. Register a zend_observer as a first step, that detects
> functions/methods with a new #[Intercept] or whatever attribute you want
> and registers observer callbacks. See ext/zend_test
> https://github.com/php/php-src/blob/master/ext/z

Re: [PHP-DEV] Built-in decorator attribute?

2021-03-13 Thread David Gebler
Decorators are a way of bringing aspect oriented programming into PHP core,
yes, among other uses.  Go AOP is a fairly bulky framework which could be
easily replaced by a Decorator attribute for the purposes of cross-cutting
changes to function behaviour.

Regards,
David

On Sat, Mar 13, 2021 at 10:51 PM Peter Stalman  wrote:

> Hi David,
>
> This sounds a lot like Asect Oriented Programming.  Have you looked into
> that?
>
> PHP framework:
> https://github.com/goaop/framework
>
> PECL extension:
> https://aop-php.github.io/
>
> Thanks,
> Peter
>
>
>
> On Sat., Mar. 13, 2021, 08:51 David Gebler,  wrote:
>
>> With the introduction of attributes in PHP 8, this new behaviour is still
>> quite sparsely documented. Some of the articles I've seen out there,
>> though, liken PHP's attributes to similar constructs in other languages
>> including decorators in Python.
>>
>> Attributes are not the same thing as (Python's concept of) decorators and
>> they shouldn't be confused; a decorator is a function which wraps another
>> function and is automatically called in place of the wrapped function.
>>
>> This isn't currently possible in PHP. Using frameworks like Symfony, we
>> can
>> start to build things like this:
>>
>> class UserProfileController {
>> #[LoginRequired]
>> public function editProfile(...) { }
>> }
>>
>> but the logic of enforcing our "require the user to be logged in"
>> decorator
>> relies on the surrounding framework controlling the flow of execution,
>> reading the attribute and deciding whether to call the decorated method
>> editProfile() at all.
>>
>> What we *can't* do is something like this:
>>
>> class Foo {
>> private function timer(callable $wrapped)
>> {
>> $start = microtime(true);
>> $wrapped();
>> $end = microtime(true);
>> $total = $end - $start;
>> echo "Executed function in $total second(s)\n";
>> }
>>
>>  #[timer]
>> public function bar($a, $b) { ... }
>>
>> #[timer]
>> public function baz($a, $b) { ... }
>> }
>>
>> What I'm wondering is whether there's a desire / interest for a built-in
>> attribute to provide this kind of behaviour modification.
>>
>> I'm thinking something like
>>
>> class Foo {
>> private function timer(callable $wrapped) { ... }
>>
>> #[Decorator([self::class, 'timer'])]
>> public function bar() {
>> echo "Bar";
>> }
>> }
>>
>> Where this would result in any call to $foo->bar() being equivalent to as
>> if the above were defined as:
>>
>> class Foo {
>> private function timer(callable $wrapped) { ... }
>>
>>  public function __bar() {
>> echo "Bar";
>>  }
>>
>> public function bar() {
>> return $this->timer([$this, '__bar']);
>> }
>> }
>>
>> I'm not saying I have the skills to implement this attribute (though I'd
>> happily try), I'm not even in a position to propose a draft RFC at this
>> stage, just throwing the idea out there to get a feel for what people
>> think
>> of the concept?
>>
>> Regards,
>> Dave
>>
>


[PHP-DEV] Re: Built-in decorator attribute?

2021-03-13 Thread David Gebler
Oops, didn't tag the subject.

On Sat, Mar 13, 2021 at 4:51 PM David Gebler  wrote:

> With the introduction of attributes in PHP 8, this new behaviour is still
> quite sparsely documented. Some of the articles I've seen out there,
> though, liken PHP's attributes to similar constructs in other languages
> including decorators in Python.
>
> Attributes are not the same thing as (Python's concept of) decorators and
> they shouldn't be confused; a decorator is a function which wraps another
> function and is automatically called in place of the wrapped function.
>
> This isn't currently possible in PHP. Using frameworks like Symfony, we
> can start to build things like this:
>
> class UserProfileController {
> #[LoginRequired]
> public function editProfile(...) { }
> }
>
> but the logic of enforcing our "require the user to be logged in"
> decorator relies on the surrounding framework controlling the flow of
> execution, reading the attribute and deciding whether to call the decorated
> method editProfile() at all.
>
> What we *can't* do is something like this:
>
> class Foo {
> private function timer(callable $wrapped)
> {
> $start = microtime(true);
> $wrapped();
> $end = microtime(true);
> $total = $end - $start;
> echo "Executed function in $total second(s)\n";
> }
>
>  #[timer]
> public function bar($a, $b) { ... }
>
> #[timer]
> public function baz($a, $b) { ... }
> }
>
> What I'm wondering is whether there's a desire / interest for a built-in
> attribute to provide this kind of behaviour modification.
>
> I'm thinking something like
>
> class Foo {
> private function timer(callable $wrapped) { ... }
>
> #[Decorator([self::class, 'timer'])]
> public function bar() {
> echo "Bar";
> }
> }
>
> Where this would result in any call to $foo->bar() being equivalent to as
> if the above were defined as:
>
> class Foo {
> private function timer(callable $wrapped) { ... }
>
>  public function __bar() {
> echo "Bar";
>  }
>
> public function bar() {
> return $this->timer([$this, '__bar']);
> }
> }
>
> I'm not saying I have the skills to implement this attribute (though I'd
> happily try), I'm not even in a position to propose a draft RFC at this
> stage, just throwing the idea out there to get a feel for what people think
> of the concept?
>
> Regards,
> Dave
>


[PHP-DEV] Built-in decorator attribute?

2021-03-13 Thread David Gebler
With the introduction of attributes in PHP 8, this new behaviour is still
quite sparsely documented. Some of the articles I've seen out there,
though, liken PHP's attributes to similar constructs in other languages
including decorators in Python.

Attributes are not the same thing as (Python's concept of) decorators and
they shouldn't be confused; a decorator is a function which wraps another
function and is automatically called in place of the wrapped function.

This isn't currently possible in PHP. Using frameworks like Symfony, we can
start to build things like this:

class UserProfileController {
#[LoginRequired]
public function editProfile(...) { }
}

but the logic of enforcing our "require the user to be logged in" decorator
relies on the surrounding framework controlling the flow of execution,
reading the attribute and deciding whether to call the decorated method
editProfile() at all.

What we *can't* do is something like this:

class Foo {
private function timer(callable $wrapped)
{
$start = microtime(true);
$wrapped();
$end = microtime(true);
$total = $end - $start;
echo "Executed function in $total second(s)\n";
}

 #[timer]
public function bar($a, $b) { ... }

#[timer]
public function baz($a, $b) { ... }
}

What I'm wondering is whether there's a desire / interest for a built-in
attribute to provide this kind of behaviour modification.

I'm thinking something like

class Foo {
private function timer(callable $wrapped) { ... }

#[Decorator([self::class, 'timer'])]
public function bar() {
echo "Bar";
}
}

Where this would result in any call to $foo->bar() being equivalent to as
if the above were defined as:

class Foo {
private function timer(callable $wrapped) { ... }

 public function __bar() {
echo "Bar";
 }

public function bar() {
return $this->timer([$this, '__bar']);
}
}

I'm not saying I have the skills to implement this attribute (though I'd
happily try), I'm not even in a position to propose a draft RFC at this
stage, just throwing the idea out there to get a feel for what people think
of the concept?

Regards,
Dave


Re: [PHP-DEV] [VOTE] fsync function

2021-03-10 Thread David Gebler
Thank you all for voting, which is now closed. This RFC has been accepted
on the final tally.

Regards
David Gebler


On Thu, Feb 25, 2021 at 2:13 PM David Gebler  wrote:

> Thanks Marco, objection understood. I think Nikita's already said what I
> would say, from my view I can only reiterate I felt it was more appropriate
> to keep the behaviour consistent with how similar stream ops work.
>
> Regards
> David Gebler
>
> On Thu, 25 Feb 2021, 13:38 Marco Pivetta,  wrote:
>
>> Het Nikita,
>>
>> On Thu, Feb 25, 2021 at 1:04 PM Nikita Popov 
>> wrote:
>>
>>>
>>> Throwing a warning in such a case is consistent with how functions for
>>> other optional stream operations work.
>>>
>>
>> I understand that, and I'm OK with being **against** it.
>>
>> Marco Pivetta
>>
>> http://twitter.com/Ocramius
>>
>> http://ocramius.github.com/
>>
>


Re: [PHP-DEV] PDO integer changes in 8.1 will stop many websites I support

2021-02-27 Thread David Gebler
Apologies, in respect of point 1 in my reply, I misread your original
message and didn't realise you were referring to the upcoming 8.1 change,
thought you were referring to the current 8.0.1 release.

This change AFAIK only affects emulated prepares and is an improvement, as
previously you needed to have emulation off to get the correct data types.
With modern PHP, MySQL and mysqnd there is not really a reason for anyone
to be using emulated prepares anyway so my advice on points 2-5 remains the
same.

Dave

On Sat, Feb 27, 2021 at 12:55 PM Stephen Reay 
wrote:

>
> > On 27 Feb 2021, at 15:56, Matty The Mad  wrote:
> >
> > PHP 8.1 PDO has been changed so that when MySQL returns an integer it
> will no longer be returned as a string, but as an int.
> >
> > The problem is this breaks any sites that use UNSIGNED ZEROFILL integer
> fields in MySQL.
> >
> > I support a number of websites where the phone numbers and post codes
> are all UNSIGNED ZEROFILL.
> >
> > The post codes in MySQL are stored as 0800.
> >
> > In PHP 8.0 returned as string 0800
> > In PHP 8.1 returned as integer 800
> >
> > 8.0.2
> > string(10) "074200"
> >
> > 8.1.0-dev
> > int(74200)
> >
> > PDO shouldn't really be changing the data.
> >
> > I propose that:
> > • any ZEROFILL integers are returned as string [or]
> > • there's an option to control this when making the connection (I don't
> want to str_pad() at every place I've used ZEROFILL in the past) [or]
> > • this backwards compatibility breaking change is removed until PHP 9.
> >
> > Matthew Asia
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
>
> I agree it should be configurable, but storing digit strings as integers
> is asking for trouble.
>
> Edit: Whoops, sending again from on-list address.
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] PDO integer changes in 8.1 will stop many websites I support

2021-02-27 Thread David Gebler
Hi Matthew,
1. PHP 8 has not introduced a change to PDO_MYSQL in respect of how values
are fetched. What makes the difference as to whether you get MySQL INT
values fetched as strings or integers is whether you are running PHP with
the mysqlnd https://dev.mysql.com/downloads/connector/php-mysqlnd/ and
emulation mode is off.

2. ZEROFILL in MySQL does not change how integers are stored, only how they
are displayed by MySQL clients. 00123 as a INT(5) ZEROFILL is still stored
as integer 123.

3. ZEROFILL is deprecated in MySQL 8. MySQL documentation advises "consider
using an alternative means of producing the effect of these attributes. For
example, applications can use the LPAD() function to zero-pad numbers up to
the desired width, or they can store the formatted numbers in CHAR columns."

4. Storing phone numbers and postal codes as integers is asking for
trouble, they are types of data which are fundamentally better represented
in storage as character types.

5. If you really need ints converted to string, turn
on PDO::ATTR_STRINGIFY_FETCHES.

Hope this helps.

Dave

On Sat, Feb 27, 2021 at 8:49 AM Matty The Mad  wrote:

> PHP 8.1 PDO has been changed so that when MySQL returns an integer it
> will no longer be returned as a string, but as an int.
>
> The problem is this breaks any sites that use UNSIGNED ZEROFILL integer
> fields in MySQL.
>
> I support a number of websites where the phone numbers and post codes
> are all UNSIGNED ZEROFILL.
>
> The post codes in MySQL are stored as 0800.
>
> In PHP 8.0 returned as string 0800
> In PHP 8.1 returned as integer 800
>
> 8.0.2
> string(10) "074200"
>
> 8.1.0-dev
> int(74200)
>
> PDO shouldn't really be changing the data.
>
> I propose that:
> • any ZEROFILL integers are returned as string [or]
> • there's an option to control this when making the connection (I don't
> want to str_pad() at every place I've used ZEROFILL in the past) [or]
> • this backwards compatibility breaking change is removed until PHP 9.
>
> Matthew Asia
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] class_name:namespace

2021-02-25 Thread David Gebler
You can achieve what you're trying to do already with a combination of
get_class() on a namespaced class and a simple regex (or other method of
processing a string to your liking):

$foo = "My\\Namespace\\Name\\Class";
var_dump(preg_match('/^(.*)\\\([^\\\]*)$/m',$foo,$matches),$matches);

array(3) {
  [0] =>
  string(23) "My\Namespace\Name\Class"
  [1] =>
  string(17) "My\Namespace\Name"
  [2] =>
  string(5) "Class"
}

Regards
David Gebler

On Thu, Feb 25, 2021 at 9:40 PM Manuel Canga  wrote:

>   En jue, 25 feb 2021 21:41:40 +0100 Nikita Popov <
> nikita@gmail.com> escribió 
>  > On Thu, Feb 25, 2021 at 8:11 PM Manuel Canga 
> wrote:
>  >
>  > > Hi internals,
>  > >
>  > > I would like to present a possible new RFC( "class_name:namespace" )
> for
>  > > your consideration.
>  > >
>  > > As you know, namespaces are very important nowdays. They are used in
>  > > autoloaders, Frameworks, CMS, ...
>  > >
>  > > Maybe, you are used to code something similar to this:
>  > >
>  > > ```
>  > > use MyProject\MyHelpers\MyClass;
>  > >
>  > > echo substr( MyClass::class, 0, strrpos( MyClass::class, '\\'));
>  > > ```
>  > >
>  > > or perhaps:
>  > >
>  > > ```
>  > > use MyProject\MyHelpers\MyClass;
>  > >
>  > > $splited_class_name = explode( '\\', MyClass::class );
>  > > array_pop($splited_class_name);
>  > > echo $namespace = implode('\\', $splited_class_name );
>  > > ```
>  > >
>  > > Other option is:
>  > >
>  > > ```
>  > > namespace MyProject\MyHelpers;
>  > >
>  > > class MyClass {
>  > >   public const NAMESPACE = __NAMESPACE__;
>  > > }
>  > > ```
>  > >
>  > > However... :(
>  > >
>  > > ```
>  > > namespace MyProject\MyServices;
>  > >
>  > > class MyNewClass  extends MyClass{
>  > > }
>  > >
>  > > echo MyNewClass::NAMESPACE; //MyProject\MyHelpers
>  > > ```
>  > >
>  > > All of these examples are ways for getting a thing which PHP compiler
>  > > would resolver fast.
>  > >
>  > > It would be fantastic can code:
>  > >
>  > > MyClass::namespace or static::namespace( for example, in abstract
> classes )
>  > >
>  > > Don't you think the same ?
>  >
>  >
>  > Could you please share the use case(s) you have in mind for this?
>  >
>  > Regards,
>  > Nikita
>
> Hi, Nikita,
>
> Yes, of course. For example, loading views using TemplateViews pattern[1]:
>
> ```
> namespace MyProjects\Framework;
>
> abstract class TemplateView {
>private const VIEW_SUBPATH = '/views/';
>
>protected function includeView( string $viewName ) {
> $filePath = str_replace('\\', '/', static::namespace ).
> self::VIEW_SUBPATH;
> $fileName =$filePath.$viewName.'.tpl';
>
> if( file_exists($fileName) ) {
> return include $fileName;
> }
>
> error_log("Not found view[$viewName] in path $filePath"  };
>}
> }
> ```
>
> ```
> namespace MyProject\CMS\Freelancer\Attachments;
>
> class Budget extends TemplateView {
>
>   public function __toString() {
>   $this->includeView('full_budget');
>   }
>
> }```
>
>
>
> Regards
> - P.S: Sorry, my mistake with subject.
>
> [1]:
> https://dzone.com/articles/practical-php-patterns/practical-php-patterns-9
> --
> Manuel Canga
>
> Zend Certified PHP Engineer
> Websites: https://manuelcanga.dev | https://trasweb.net
> Linkedin: https://es.linkedin.com/in/manuelcanga
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [VOTE] fsync function

2021-02-25 Thread David Gebler
Thanks Marco, objection understood. I think Nikita's already said what I
would say, from my view I can only reiterate I felt it was more appropriate
to keep the behaviour consistent with how similar stream ops work.

Regards
David Gebler

On Thu, 25 Feb 2021, 13:38 Marco Pivetta,  wrote:

> Het Nikita,
>
> On Thu, Feb 25, 2021 at 1:04 PM Nikita Popov  wrote:
>
>>
>> Throwing a warning in such a case is consistent with how functions for
>> other optional stream operations work.
>>
>
> I understand that, and I'm OK with being **against** it.
>
> Marco Pivetta
>
> http://twitter.com/Ocramius
>
> http://ocramius.github.com/
>


Re: [PHP-DEV] [VOTE] fsync function

2021-02-24 Thread David Gebler
Voting is now open for 2 weeks on https://wiki.php.net/rfc/fsync_function

Regards,
David Gebler

On Tue, Feb 23, 2021 at 5:15 PM David Gebler  wrote:

> Hi internals,
> As there appear to be no objections or concerns, I intend to open voting
> on https://wiki.php.net/rfc/fsync_function tomorrow and voting will
> remain open for two weeks.
>
> The RFC and its implementation
>
> - Adds functions fsync() and fdatasync() for plain file streams on Unix
> systems.
> - Adds function fsync() on Windows with fdatasync() available as an alias
>
> PR ref https://github.com/php/php-src/pull/6650
>
> Regards,
> David Gebler
>


[PHP-DEV] [VOTE] fsync function

2021-02-23 Thread David Gebler
Hi internals,
As there appear to be no objections or concerns, I intend to open voting on
https://wiki.php.net/rfc/fsync_function tomorrow and voting will remain
open for two weeks.

The RFC and its implementation

- Adds functions fsync() and fdatasync() for plain file streams on Unix
systems.
- Adds function fsync() on Windows with fdatasync() available as an alias

PR ref https://github.com/php/php-src/pull/6650

Regards,
David Gebler


Re: [PHP-DEV] [RFC] fsync function

2021-02-10 Thread David Gebler
Hi all,
Giving this one a little bump as I haven't had any particular feedback or
comments about it so far. I know it's not the biggest or most exciting
change in the world but it's implemented and I'd like to progress it to a
vote in another week or so if there are no objections or clarifications? To
summarise:

- Adds fsync() and fdatasync() for plain file streams on Unix systems.
- Adds fsync() on Windows with fdatasync() as an alias.

Thank you.

RFC ref: https://wiki.php.net/rfc/fsync_function
PR ref: https://github.com/php/php-src/pull/6650

-Dave

On Wed, Feb 3, 2021 at 5:46 PM David Gebler  wrote:

> RFC ref: https://wiki.php.net/rfc/fsync_function
> PR ref: https://github.com/php/php-src/pull/6650
>
> I think this one is pretty much good now and passing builds; when I first
> proposed adding fsync some time ago, there was a suggestion from a couple
> contributors that an RFC might be overkill/unnecessary for this feature
> (and I'd certainly be happy for it to just be accepted as a pull request)
> but want to make sure everyone has had a good chance to look over the RFC
> and implementation and specifically whether anyone has any significant
> concerns or objections?
>
> Thanks.
>
> Dave
>
> On Mon, Feb 1, 2021 at 5:35 PM David Gebler  wrote:
>
>> Hi internals,
>> I have updated the GitHub PR and wiki RFC to also include an
>> implementation of fdatasync.
>>
>> On another note, I note my PR builds are failing on MACOS_DEBUG_NTS with
>> a test in ext/zend_test/tests/observer_error_05.phpt- this does not
>> appear to be related to my changes and I'm wondering if anyone can shed
>> any light on this? I'm seeing it on some other open PRs too so I'm guessing
>> it's a known issue? Cheers.
>>
>> David Gebler
>> davidgeb...@gmail.com
>>
>>
>> On Sat, Jan 30, 2021 at 6:34 PM David Gebler 
>> wrote:
>>
>>> Updated the PR https://github.com/php/php-src/pull/6650 following
>>> comment from Nikita, added basic tests, would appreciate further review
>>> from contributors, have updated the RFC
>>> https://wiki.php.net/rfc/fsync_function to under discussion, cheers.
>>>
>>> David Gebler
>>> davidgeb...@gmail.com
>>>
>>>
>>> On Sat, Jan 30, 2021 at 1:58 AM David Gebler 
>>> wrote:
>>>
>>>> Hi internals,
>>>> Some time back I asked for commentary on a proposal to add fsync() to
>>>> PHP, I have now submitted a draft RFC
>>>> https://wiki.php.net/rfc/fsync_function alongside an in-progress proof
>>>> of concept PR (current status: can compile locally and run but the branch
>>>> needs more work to bring it up to standard, as well as tests and
>>>> documentation) which I would like to open up for review and discussion.
>>>>
>>>> Thanks.
>>>>
>>>> David Gebler
>>>> davidgeb...@gmail.com
>>>>
>>>>


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

2021-02-06 Thread David Gebler
This is all a bit moot anyway, the RFC proposal is for warnings or notices
on implicit casts only.

I'm not a voting member for RFCs so my opinion is mere food for thought,
nonetheless my two cents is that:

a) The proposal relies on a premise that an implicit cast of (non-zero
fractional) float to int is inherently ambiguous or a mistake.
I disagree with this as outlined in my previous messages; namely my
objection is truncating a float on cast to int is the widely established
normal behaviour in numerous programming languages.
There should not be a penalty in the form of an error just for doing such a
conversion implicitly, in accordance with how PHP's type coercion works by
design.

b) String offsets, where a warning occurs already, is something of a
special case; this warning was added I believe (5.4?) because malformed
string offset was a known common error in the community. It's not even
entirely consistent; $foo["2"] is fine, $foo[2.5] is a warning with offset
[2], $foo["2x"] is a warning with offset [2] and $foo["2.5"] is a TypeError.

c) It's a substantial BC breaking change likely to affect a lot of existing
code, even though that code works as intended.

d) If it is implemented at all, it should not be an error level as high as
a warning.

-Dave

On Sat, Feb 6, 2021 at 7:32 PM Rowan Tommins 
wrote:

> On 06/02/2021 14:47, Christian Schneider wrote:
> > I'm sure there is a lot of code which takes user input and uses (int)
> casts to ensure they are dealing with integers.
> > There is also intval() as an alternative but my guess would be that real
> world code uses 50% (int) and 50% intval() to do this.
>
>
> My thoughts exactly. Code along these lines is common and, in my
> opinion, perfectly reasonable:
>
> $id = (int)$_GET['id'];
> if ( $id !== 0 ) {
>   // throw an exception, return false, look up a default, etc, as
> the application's design requires
> }
> // proceed knowing that $id is a non-zero integer
>
>
> I would however welcome a new function or syntax that either performs a
> "strict cast" (producing an error if the cast is lossy in any way) or
> checks in advance if a cast *would be* lossy.
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> 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 David Gebler
> 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.

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).


On Fri, Feb 5, 2021 at 12:52 PM Benjamin Morel 
wrote:

> 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] Interaction between finally blocks and exit()

2021-02-05 Thread David Gebler
Interesting. I'm not sure there's a "correct" answer here, but FWIW on
balance my feeling is the expectation that exit() will immediately
terminate a script (registered shutdown functions and destructors aside)
should take precedence over the expectation that finally blocks will always
execute, just because if you've got an exit/die inside a try block, I think
it is reasonable to expect that you have already done anything that needs
to be done before you get there (i.e. that your intent is for nothing else
to happen), or to consider it a bug (certainly eyebrow raising code smell)
otherwise. It's not the kind of use case finally was conceptually intended
to address. And unlike an explicitly declared and self contained shutdown
function or destructor, this could lead to what is effectively shutdown
code being far removed and in a seemingly-random place in the code in
relation to where the exit call occurs, maybe in a different file and not
obvious to track down.

Dave


On Fri, Feb 5, 2021 at 1:10 PM G. P. B.  wrote:

> Greetings internals,
>
> While working on rewriting the PHP docs about errors and error handling [1]
> I came across a change of behaviour in an edge case of an edge case.
>
> finally blocks are meant to be always executed regardless that an Exception
> has been thrown or not, which it does, however a call to exit() (or die()
> as they are aliases).
> This can be seen with the following example: https://3v4l.org/6Tger
>
> However, there is one case where finally blocks are executed when exit() is
> used, namely when a generator has a finally block and exit() is called
> during its traversal, an example of this in action can be seen here:
> https://3v4l.org/HGKHS
>
> The behaviour of this edge case of an edge case is highly dependent on the
> version of PHP where this is run, PHP 5.5, 5.6, 7.0, early version of PHP
> 7.1, PHP 7.2.0, PHP 7.2.1, and PHP 8.0 all run the finally block on exit().
> Later versions of PHP 7.1, 7.2.2 and above and PHP 7.3 and 7.4 all skip the
> finally block.
>
> Frankly this is already going to be a mess to document, but this begs the
> question is there a "bug" in executing the finally blocks in generators
> during a call to exit() or is the "bug" to not execute finally blocks when
> exit() is called.
>
> I've CCed the PHP 8.0 RMs as if the consensus is that skipping finally
> blocks after a call to exit() is performed it would be wise to change this
> behaviour in PHP 8.0 only and land this ASAP, even though it's a BC break.
>
> Interested in hearing your thoughts.
>
> Best regards,
>
> George P. Banyard
>
> [1] https://github.com/php/doc-en/pull/320
>


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

2021-02-04 Thread David Gebler
> Except that example is ambiguous.  Specifically, which is more logical,
to truncate it to 3 or round it up to 4?  It probably depends heavily on
your context.  Implicitly doing one or the other can result in surprises.

I disagree this is ambiguous. The integral portion of a float is what it
is, any notion of rounding it up is no more relevant here than multiplying
by it 20, calculating it's sin value or anything else you can do with a
number. These are operations you explicitly choose to perform on a scalar.

On Thu, Feb 4, 2021 at 7:22 PM Larry Garfield 
wrote:

> On Thu, Feb 4, 2021, at 12:06 PM, David Gebler wrote:
> > If this were to be done, my gut feeling is a notice would be preferable
> to
> > a warning, particularly as there must be many scripts which would
> suddenly
> > start churning out warnings for this proposed change which might/probably
> > ignore lower error levels and emitting a warning for a previously common
> > script behaviour is quite a significant backwards incompatible change.
> >
> > The bit which makes me more nervous about the proposed change is your
> > rationale that implicit float to int conversion dropping the fractional
> > portion means there is "no way to know if the data provided is
> erroneous".
> >
> > I get the idea behind your proposal, but equally I'm not convinced this
> is
> > comparable to numeric vs non-numeric or malformed/partially numeric
> > strings. There isn't any value of the string "foobar" which makes sense
> as
> > an integer. But there is a value for a float which makes sense as an
> > integer; the integral part. In the float 3.81232 the integral portion 3
> is
> > completely unambiguous. It's not like it would make just as much sense to
> > interpret it as any other arbitrary integer value.
>
> Except that example is ambiguous.  Specifically, which is more logical, to
> truncate it to 3 or round it up to 4?  It probably depends heavily on your
> context.  Implicitly doing one or the other can result in surprises.
>
>
> My main concern is if you're casting floats to ints and the floats are
> usually ints anyway, and so no error, you may not even realize the error
> remains for a long time until you suddenly start getting a warning if your
> incoming data shifts.  I have no idea how common that pattern is in
> practice, though.
>
> --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-04 Thread David Gebler
If this were to be done, my gut feeling is a notice would be preferable to
a warning, particularly as there must be many scripts which would suddenly
start churning out warnings for this proposed change which might/probably
ignore lower error levels and emitting a warning for a previously common
script behaviour is quite a significant backwards incompatible change.

The bit which makes me more nervous about the proposed change is your
rationale that implicit float to int conversion dropping the fractional
portion means there is "no way to know if the data provided is erroneous".

I get the idea behind your proposal, but equally I'm not convinced this is
comparable to numeric vs non-numeric or malformed/partially numeric
strings. There isn't any value of the string "foobar" which makes sense as
an integer. But there is a value for a float which makes sense as an
integer; the integral part. In the float 3.81232 the integral portion 3 is
completely unambiguous. It's not like it would make just as much sense to
interpret it as any other arbitrary integer value.

So in these cases, via coercion you're just straightforwardly giving a
valid, unambiguous integer to something which expects an integer. I'd
question why should that raise a warning or TypeError.

In favour of the proposal are a couple of the other issues you mentioned
which mean this would make PHP a bit more consistent all-round...but I'm
not entirely persuaded at this point.

-Dave

On Thu, Feb 4, 2021 at 4:05 PM 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
>


[PHP-DEV] Re: [RFC]: fsync function

2021-02-03 Thread David Gebler
RFC ref: https://wiki.php.net/rfc/fsync_function
PR ref: https://github.com/php/php-src/pull/6650

I think this one is pretty much good now and passing builds; when I first
proposed adding fsync some time ago, there was a suggestion from a couple
contributors that an RFC might be overkill/unnecessary for this feature
(and I'd certainly be happy for it to just be accepted as a pull request)
but want to make sure everyone has had a good chance to look over the RFC
and implementation and specifically whether anyone has any significant
concerns or objections?

Thanks.

Dave

On Mon, Feb 1, 2021 at 5:35 PM David Gebler  wrote:

> Hi internals,
> I have updated the GitHub PR and wiki RFC to also include an
> implementation of fdatasync.
>
> On another note, I note my PR builds are failing on MACOS_DEBUG_NTS with a
> test in ext/zend_test/tests/observer_error_05.phpt- this does not appear
> to be related to my changes and I'm wondering if anyone can shed any light
> on this? I'm seeing it on some other open PRs too so I'm guessing it's a
> known issue? Cheers.
>
> David Gebler
> davidgeb...@gmail.com
>
>
> On Sat, Jan 30, 2021 at 6:34 PM David Gebler 
> wrote:
>
>> Updated the PR https://github.com/php/php-src/pull/6650 following
>> comment from Nikita, added basic tests, would appreciate further review
>> from contributors, have updated the RFC
>> https://wiki.php.net/rfc/fsync_function to under discussion, cheers.
>>
>> David Gebler
>> davidgeb...@gmail.com
>>
>>
>> On Sat, Jan 30, 2021 at 1:58 AM David Gebler 
>> wrote:
>>
>>> Hi internals,
>>> Some time back I asked for commentary on a proposal to add fsync() to
>>> PHP, I have now submitted a draft RFC
>>> https://wiki.php.net/rfc/fsync_function alongside an in-progress proof
>>> of concept PR (current status: can compile locally and run but the branch
>>> needs more work to bring it up to standard, as well as tests and
>>> documentation) which I would like to open up for review and discussion.
>>>
>>> Thanks.
>>>
>>> David Gebler
>>> davidgeb...@gmail.com
>>>
>>>


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

2021-02-01 Thread David Gebler
> We tried that.  The `enum` keyword precludes any class or interface being
called `Enum`, even internally.

Enumerable, Enumerated, Enumerator?

On Mon, Feb 1, 2021 at 7:30 PM Larry Garfield 
wrote:

> On Mon, Feb 1, 2021, at 11:48 AM, Alexandru Pătrănescu wrote:
>
>
> > > https://wiki.php.net/rfc/enumerations
> > >
> > > At this point, Ilija and I consider the RFC done and ready for a vote.
> > > Baring any major issues being brought up, we plan to start the vote in
> the
> > > first half of next week, probably Tuesday-ish.  If you have any other
> bug
> > > reports or tweaks, please speak now or forever hold your patches.
> > >
> > > --Larry Garfield
> > >
> > >
> > Hi,
> >
> > Maybe IterableEnum can actually be just Enum. As you are not allowed to
> > implement it and/or define it, wouldn't it work? That's how it's named
> > internally in Java, not that it would matter but sometimes people forget
> > it's just syntactic sugar there as well (
> > https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html): public
> > abstract class Enum> implements Comparable,
> > Serializable.
>
> We tried that.  The `enum` keyword precludes any class or interface being
> called `Enum`, even internally.
>
> > Also in the interface I think you can include the name property,
> similarly
> > with how you did in BackedEnum interface.
> > https://wiki.php.net/rfc/property_accessors will probably allow it to be
> > clearly defined at some point.
> >
> > A bit it bothers me that backed enums are very easy to implement even
> > without the special case and just a simple Enum would be fine.
> > I mean even if you will have a backed enum, with would be simple and
> > probably the need will come at some point to have also a public function
> > getLegacyValue(): string and a public static function
> > fromLegacyValue(string $value): Enum.
> > But yes, using backed values is a common pattern so I'm guessing it's a
> > valuable important use case.
>
> It's more about standardizing the API.  An ORM can rely on a backed enum
> always exposing its "value to save to the DB" at ->value, rather than it
> sometimes being ->value(), sometimes ->legacyValue(), sometimes ->asInt(),
> etc.
>
> > For storing in a database purpose, property name can be used directly, I
> > think.
> > It would nice to have in the rfc the recommended way to retrieve the
> Enum,
> > given that you know the name.
> > I'm guessing that would be Suit::$name;
>
> That doesn't work for referencing a constant; it gets read as a static
> property.  That's a more general syntactic question for PHP, and one we're
> not going to solve here. :-)  Really, ->name is more an implementation
> artifact.  If you want to have a primitive to pass around, for whatever
> reason, that's what a backed enum is for.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


[PHP-DEV] Re: [RFC]: fsync function

2021-02-01 Thread David Gebler
Hi internals,
I have updated the GitHub PR and wiki RFC to also include an implementation
of fdatasync.

On another note, I note my PR builds are failing on MACOS_DEBUG_NTS with a
test in ext/zend_test/tests/observer_error_05.phpt- this does not appear to
be related to my changes and I'm wondering if anyone can shed any light on
this? I'm seeing it on some other open PRs too so I'm guessing it's a known
issue? Cheers.

David Gebler
davidgeb...@gmail.com


On Sat, Jan 30, 2021 at 6:34 PM David Gebler  wrote:

> Updated the PR https://github.com/php/php-src/pull/6650 following comment
> from Nikita, added basic tests, would appreciate further review from
> contributors, have updated the RFC https://wiki.php.net/rfc/fsync_function to
> under discussion, cheers.
>
> David Gebler
> davidgeb...@gmail.com
>
>
> On Sat, Jan 30, 2021 at 1:58 AM David Gebler 
> wrote:
>
>> Hi internals,
>> Some time back I asked for commentary on a proposal to add fsync() to
>> PHP, I have now submitted a draft RFC
>> https://wiki.php.net/rfc/fsync_function alongside an in-progress proof
>> of concept PR (current status: can compile locally and run but the branch
>> needs more work to bring it up to standard, as well as tests and
>> documentation) which I would like to open up for review and discussion.
>>
>> Thanks.
>>
>> David Gebler
>> davidgeb...@gmail.com
>>
>>


[PHP-DEV] Re: [RFC]: fsync function

2021-01-30 Thread David Gebler
Updated the PR https://github.com/php/php-src/pull/6650 following comment
from Nikita, added basic tests, would appreciate further review from
contributors, have updated the RFC https://wiki.php.net/rfc/fsync_function to
under discussion, cheers.

David Gebler
davidgeb...@gmail.com


On Sat, Jan 30, 2021 at 1:58 AM David Gebler  wrote:

> Hi internals,
> Some time back I asked for commentary on a proposal to add fsync() to PHP,
> I have now submitted a draft RFC https://wiki.php.net/rfc/fsync_function
> alongside an in-progress proof of concept PR (current status: can compile
> locally and run but the branch needs more work to bring it up to standard,
> as well as tests and documentation) which I would like to open up for
> review and discussion.
>
> Thanks.
>
> David Gebler
> davidgeb...@gmail.com
>
>


[PHP-DEV] [RFC]: fsync function

2021-01-29 Thread David Gebler
Hi internals,
Some time back I asked for commentary on a proposal to add fsync() to PHP,
I have now submitted a draft RFC https://wiki.php.net/rfc/fsync_function
alongside an in-progress proof of concept PR (current status: can compile
locally and run but the branch needs more work to bring it up to standard,
as well as tests and documentation) which I would like to open up for
review and discussion.

Thanks.

David Gebler
davidgeb...@gmail.com


Re: [PHP-DEV] RFC proposal: fsync support for file resources

2020-06-05 Thread David Gebler
Thanks, my browser was automatically populating the wrong email, I've now
registered. Apparently I need to request karma now? Username dwgebler.

On Sat, Jun 6, 2020 at 12:19 AM Christoph M. Becker 
wrote:

> On 06.06.2020 at 00:00, David Gebler wrote:
>
> > As a side-note, I am unable to register a wiki.php.net account to raise
> > this RFC, I get a very unhelpful error message which just says "That
> wasn't
> > the answer we were expecting" when I submit my details. Anyone have any
> > idea what that is?
>
> I assume you're stumbling upon the CAPTCHA (fourth input field).  The
> point is, after registration you are supposed to send a mail to this
> mailing list; and that email address is asked for. :)
>
> --
> Christoph M. Becker
>


Re: [PHP-DEV] RFC proposal: fsync support for file resources

2020-06-05 Thread David Gebler
As a side-note, I am unable to register a wiki.php.net account to raise
this RFC, I get a very unhelpful error message which just says "That wasn't
the answer we were expecting" when I submit my details. Anyone have any
idea what that is?

On Thu, Jun 4, 2020 at 3:19 PM David Gebler  wrote:

> It's interesting that you mention fdatasync - perhaps a better C
> programmer than I am can correct me, but I don't think it has an equivalent
> on Windows, where _commit() is a wrap on FlushFileBuffers API. So in
> respect of PHP implementation, the options would be:
>
> fdatasync() is not available on Windows, but fsync() is. fdatasync() is
> available on UNIX builds.
>
> fdatasync() on Windows is an alias of fsync(), on UNIX fdatasync() is as
> expected.
>
> Only fsync() is implemented for both Windows and Unix.
>
> -Dave
>
> On Wed, 3 Jun 2020, 11:16 Nikita Popov,  wrote:
>
>> On Mon, Jun 1, 2020 at 6:57 PM David Gebler 
>> wrote:
>>
>>> Exactly as the subject says, I would like to propose an RFC for adding an
>>> fsync() function for file resources, which would in essence be a thin
>>> wrapper around C's fsync on UNIX systems and _commit on Windows.
>>>
>>> It seems to me an odd oversight that this has never been implemented in
>>> PHP
>>> and means PHP has no way to perform durable file write operations, making
>>> it inherently unsuitable for any systems requiring more intensive I/O,
>>> mission critical logs, auditing, etc.
>>>
>>> I am not really a C programmer and I have been able to implement a simple
>>> working prototype of this as a compiled extension in merely a few hours,
>>> so
>>> I'm sure it wouldn't be difficult to bring in to the language core where
>>> the functionality really belongs.
>>>
>>> Every other major programming language otherwise comparable to PHP in
>>> features supports a way of providing durability.
>>>
>>> Thanks.
>>>
>>
>> No objections from my side. I assume you'd want to add both fsync() and
>> fdatasync()?
>>
>> I think all it takes for this one is a PR...
>>
>> Regards,
>> Nikita
>>
>


Re: [PHP-DEV] RFC proposal: fsync support for file resources

2020-06-04 Thread David Gebler
It's interesting that you mention fdatasync - perhaps a better C programmer
than I am can correct me, but I don't think it has an equivalent on
Windows, where _commit() is a wrap on FlushFileBuffers API. So in respect
of PHP implementation, the options would be:

fdatasync() is not available on Windows, but fsync() is. fdatasync() is
available on UNIX builds.

fdatasync() on Windows is an alias of fsync(), on UNIX fdatasync() is as
expected.

Only fsync() is implemented for both Windows and Unix.

-Dave

On Wed, 3 Jun 2020, 11:16 Nikita Popov,  wrote:

> On Mon, Jun 1, 2020 at 6:57 PM David Gebler  wrote:
>
>> Exactly as the subject says, I would like to propose an RFC for adding an
>> fsync() function for file resources, which would in essence be a thin
>> wrapper around C's fsync on UNIX systems and _commit on Windows.
>>
>> It seems to me an odd oversight that this has never been implemented in
>> PHP
>> and means PHP has no way to perform durable file write operations, making
>> it inherently unsuitable for any systems requiring more intensive I/O,
>> mission critical logs, auditing, etc.
>>
>> I am not really a C programmer and I have been able to implement a simple
>> working prototype of this as a compiled extension in merely a few hours,
>> so
>> I'm sure it wouldn't be difficult to bring in to the language core where
>> the functionality really belongs.
>>
>> Every other major programming language otherwise comparable to PHP in
>> features supports a way of providing durability.
>>
>> Thanks.
>>
>
> No objections from my side. I assume you'd want to add both fsync() and
> fdatasync()?
>
> I think all it takes for this one is a PR...
>
> Regards,
> Nikita
>


Re: [PHP-DEV] RFC proposal: fsync support for file resources

2020-06-01 Thread David Gebler
fsync() does not *guarantee* data has been persisted because no software
mechanism which exists can do that. It is however the *best assurance* we
can have that data has been physically persisted by the time the function
returns.

fsync() is the best operating-system level assurance we can get regarding
data persistence and PHP is the only major programming language I can think
of which doesn't support a means of doing it. I've had use cases in web
systems and microservices written in PHP where the ability to provide
durable file writes would have been very valuable, other cases where
services have had to be written in Java or some other language specifically
because they require durability where PHP might otherwise have been a good
candidate.

> While there is little reason not to add fsync() to PHP the importance and
benefits are IMHO not that big.

Arguably so, but neither that big is the effort required to implement this
feature.

On Mon, Jun 1, 2020 at 8:47 PM Christian Schneider 
wrote:

> Am 01.06.2020 um 18:56 schrieb David Gebler :
> > It seems to me an odd oversight that this has never been implemented in
> PHP
> > and means PHP has no way to perform durable file write operations, making
> > it inherently unsuitable for any systems requiring more intensive I/O,
> > mission critical logs, auditing, etc.
>
> I think there is a misconception of the usefulness of fsync() here.
>
> First of all it does not *really* guarantee the data is safe from power
> outages etc, see
> https://stackoverflow.com/a/706688
> https://stackoverflow.com/a/725742
> and other answers in that thread.
>
> Secondly I'd rather rely on something like a proper DB if not losing any
> data is crucial.
> Trying to implement it in pure PHP and plain old files seems like using
> the wrong tools for the job to me.
>
> While there is little reason not to add fsync() to PHP the importance and
> benefits are IMHO not that big.
>
> - Chris
>
>


Re: [PHP-DEV] RFC proposal: fsync support for file resources

2020-06-01 Thread David Gebler
Just to add and clarify; operating systems have their own internal write
buffers. When you call fflush() you are saying "immediately flush this data
from my program buffers to the operating system".

When you call fsync() you are saying "immediately flush this data from my
program buffers to the operating system *and tell the operating system to
immediately flush its buffer to disk too*", so when this function returns
success status you can be as reliably sure as possible that data has been
physically persisted. fflush does not provide this assurance.

On Mon, 1 Jun 2020, 18:52 David Gebler,  wrote:

> No, fflush will flush the PHP application buffers out to the operating
> system, it does in contrast to fsync not provide a guarantee the operating
> system will immediately persist to the underlying storage device.
>
> On Mon, 1 Jun 2020, 18:49 Dennis Birkholz, 
> wrote:
>
>> Hello David,
>>
>> isn't fflush exactly this:
>> https://www.php.net/manual/en/function.fflush.php
>>
>> Greets
>> Dennis
>>
>> Am 01.06.20 um 18:56 schrieb David Gebler:
>> > Exactly as the subject says, I would like to propose an RFC for adding
>> an
>> > fsync() function for file resources, which would in essence be a thin
>> > wrapper around C's fsync on UNIX systems and _commit on Windows.
>> >
>> > It seems to me an odd oversight that this has never been implemented in
>> PHP
>> > and means PHP has no way to perform durable file write operations,
>> making
>> > it inherently unsuitable for any systems requiring more intensive I/O,
>> > mission critical logs, auditing, etc.
>> >
>> > I am not really a C programmer and I have been able to implement a
>> simple
>> > working prototype of this as a compiled extension in merely a few
>> hours, so
>> > I'm sure it wouldn't be difficult to bring in to the language core where
>> > the functionality really belongs.
>> >
>> > Every other major programming language otherwise comparable to PHP in
>> > features supports a way of providing durability.
>> >
>> > Thanks.
>> >
>>
>>


  1   2   >