Re: [PHP-DEV] [Discussion] Implementing interfaces via traits

2024-08-29 Thread Michał Marcin Brzuchalski
Hi Brent,

wt., 27 sie 2024 o 09:28 Brent Roose  napisał(a):

> Good morning internals
>
> I’d like to test the waters about an RFC idea: allowing traits to
> implement interfaces, and consequently a class that uses such a trait will
> automatically implement the interface as well.
>
> The original idea comes from Rust, where traits can be used as types. I
> read a very inspiring post suggested by Larry, on the topic of “classic
> inheritance” vs the way Rust and Go approach it [1]. The tl;dr is that both
> Rust and Go solve several pitfalls of classical inheritance (the diamond
> problem and inheritance abuse), thanks to a much simpler approach. In
> Rust’s case that is by using traits. If you have the time, I highly
> recommend reading that post, it’s super interesting and it gives a lot of
> good arguments for rethinking inheritance.
>
> Back to PHP, using traits as types seems impossible, since traits are a
> compile-time copy/paste mechanism, which means there’s no type information
> available about them at runtime.
>
> However, allowing traits to implement interfaces would solve this problem:
> these interfaces would be copied over to classes during compile-time, and
> the interface’s type information is available at runtime. On top of that,
> traits already have well-defined rules for conflict resolution, so we
> wouldn’t need any additional syntax to handle edge cases.
>
> Even though PHP traits differ from Rust, PHP developers already seem to
> like the idea of being able to “attach a type to a trait” one way or
> another. Let me name a couple of things that happen today:
>
>
>-
>
>Laravel often provides “default implementations” for their interfaces
>via a trait [2]. As mentioned before, traits already deal with
>conflict-resolution, so method collisions aren’t a blocker.
>-
>
>Both PHPStan and Psalm have an annotation that forces trait users to
>implement an interface [3], which is essentially the feature I’m
>describing, albeit via docblock annotations instead of proper syntax.
>-
>
>Even though it was not accepted, the interface default methods RFC
>approached the problem from a different angle [4]. While a majority
>disagreed that interfaces should implement their own methods directly, I
>remember it was a heavily debated topic, and believe that approaching it
>from the other side might be easier to accept.
>
>

With the recent RFC proposal for Default Expressions
<https://wiki.php.net/rfc/default_expression> [5], I believe it presents an
excellent opportunity to revisit the Interface Default Methods proposal.
The Default Expressions RFC addresses similar functionality and, when
combined with an opt-in feature flag, could resolve many concerns raised
during the previous discussion.

*Opt-In Feature Flag:* To address backward compatibility concerns, I
propose the introduction of a feature flag, such as declare(default_methods
= 1);, that could be applied when implementing an interface or when an
interface extends another. This approach would allow developers to opt-in
explicitly, preventing unintended BC breaks and ensuring that the feature
is adopted carefully and intentionally.

*Backward Compatibility Concerns:* The main concern from the previous
discussion was the risk of BC breaks when new methods are added to an
interface, potentially conflicting with existing implementations. Although
the original RFC suggested that default implementations could mitigate
these risks, contributors were worried that this might encourage developers
to introduce BC breaks without proper versioning. The opt-in flag would
make it clear when the feature is being used, thereby reducing the risk of
unintentional conflicts.

*Complexity and Developer Experience:* While the feature could
significantly improve the developer experience, it also introduces
complexity in how interfaces are used. To alleviate this, the default
keyword could be explicitly used to mark default methods, making it easier
for developers to understand and manage. For example:

interface I1 {
default public function foo(): int {
return \PHP_INT_MAX;
}
}

This explicit marking not only clarifies the intention behind the method
but also aids in distinguishing between regular and default methods,
simplifying the mental model required to work with interfaces.

I believe these adjustments could make the Interface Default Methods more
palatable to the community, ensuring that the feature enhances PHP without
introducing unnecessary risks.

Just thinking out loud here - looking forward to hearing some thoughts.

Cheers,
Michał Marcin Brzuchalski

*Links:*
[4] Interface Default Methods RFC
<https://wiki.php.net/rfc/interface-default-methods>
[5] Default Expressions RFC <https://wiki.php.net/rfc/default_expression>


Re: [PHP-DEV] Packages Iteration 3: was Re: [PHP-DEV] [Initial Feedback] PHP User Modules - An Adaptation of ES6 from JavaScript

2024-06-30 Thread Michał Marcin Brzuchalski
Hi Michael,

pon., 1 lip 2024 o 01:18 Michael Morris  napisał(a):

> ...
> Applications
>
> The application is the root package. It is the package that imports to the
> root namespace. When PHP is asked to parse a file it will look for a
> `.php-packages` folder, first in the current working directory then in
> parent directories.  If it doesn't find one, business as usual.  If we do
> find one we follow its directives about setting up an application
> environment.
>
> The `.php-packages` folder is where PHP will put package related code for
> the application at hand.  Code written explicitly for these changes will
> also put their package related files there - composer's vendor directory,
> composer.json, composer.lock, and so on - rather than putting those files
> in the site root. The folder is hidden to prevent web servers like nginx or
> apache from serving the files directly in any way.
>

First, you use the term Application then Site - decide.
Not all PHP applications are HTTP Applications, consider consumers, cron
tasks other daemons, these don't need the existence of either Nginx or
Apache.
Not all PHP HTTP Applications expose files to Nginx or Apache - most of
these I know like Rest API give ZERO access to any application file to
Nginx or Apache.


> The .php-packages directory will have a configuration file called
> `php.mod`.  This tells the parser:
>

You propose to move `composer.json`, `composer.lock`, and `vendor` into a
hidden folder with no good reason which simply adds more confusion.


> Let's look at what such a file might look like for Drupal. For the moment
> I'm going to use go.mod's syntax. The final syntax to be used, be it ini,
> yaml, toml, json, is a discussion for another time. The part to focus in on
> here is what type of information do we need.
>
>   package Drupal
>
>   php 10
>
>   registry //packagist.org/packages composer
>
>   init (
> composer install
>   )
>
>   require (
> ./vendor/autoload.php
>   )
>
>   imports (
> //getcomposer.org/composer.phar
>   )
>

This looks like a completely new file format which simply makes
interoperability harder, consider tools like GitHub Dependabot, PHPMetrics
or other tools that analyze dependencies - what you propose requires
implementing a parser in userland or other languages the tool uses.


> The directives do the following:
> ...
>
* init is the command(s) to run before the application is started for the
> first time.
>

What is the use case for it I don't get it.
Many PHP Applications are distributed as a container image with all
dependencies already included.
How would it work with multi-threaded environments, which thread would be
responsible for running init? How do you solve concurrency problems then?


> If this theoretical version of Drupal moves its composer.json and
> composer.lock files into `.php-packages` then the autoloader doesn't have
> to be required in the index.php file.  Also, the application can be started
> without running `composer install`
>

`index.php` is just a common name for PHP HTTP Applications for modern
frameworks like Symfony and others that one lays in `public/` folder as an
entry point, often this is the only file in this directory.
If I understand your idea correctly you'd like a couple of I/O operations
on the filesystem to find the `.php-packages` directory in CWD else if not
in the parent directory and so on rather than directly pointing where it
is, right?


Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [Initial Feedback] Typed Arrays

2024-06-30 Thread Michał Marcin Brzuchalski
pon., 1 lip 2024 o 03:01 Larry Garfield  napisał(a):

> On Sun, Jun 30, 2024, at 11:13 AM, Michał Marcin Brzuchalski wrote:
> > Hi Richard,
> >
> > czw., 27 cze 2024, 22:33 użytkownik Richard Miles
> >  napisał:
> >>
> >> > I worked with Joe Watkins to do a proof-of-concept for generic traits.
> >> > It's a bit old since it's from 2017, but could be a useful starting
> >> > point if you are serious about pursuing this idea:
> >> >
> >> >
> https://github.com/php/php-src/compare/master...morrisonlevi:php-src:parameterized_traits
> >>
> >>
> >> I’m also interested in this; it will help see branches like these.
> >> Did you ever get the POC working? What did you feel like was the
> biggest hurdle?
> >
> > There even was an RFC in voting which Joe implemented and it addresses
> > nearly what is discussed it this thread https://wiki.php.net/rfc/arrayof
> >
> > I must admit that the collection proposal is bit too complex to
> > address such tiny but powerfully in my opinion functionality which is
> > typed array. What Derick showed looks more like generic collection and
> > such require declaring it's type. In my opinion this is way too mush
> > hassle to declare as many collection types as many usages in
> > application. Also two collection types with the same collection item
> > type will not be compatible from type perspective. While typed array
> > seems much more clear and compatible in all places where typed array is
> > needed without declaring separate type for each usage.
> >
> > If I were to choose between typed-array and collection like Derick
> > showed a little bit I'd choose typed arrays definitely as a first
> > feature to be merged into PHP.
> >
> > Cheers,
> > Michał Marcin Brzuchalski
>
> Contextual point: Nearly every other major language at this point that has
> a meaningful standard library has gone with a three-separate-object
> approach (Seq, Set, Dict, called various things).  At least Python,
> Javascript, Rust, Kotlin, and Swift, in my research.  (Go doesn't, but Go
> avoids having features by design.)  And AFAIK *every* language except PHP
> and Lua separates sequences from dictionaries.  Typed arrays will not full
> resolve the seq vs dict problem, which is arguably PHP's original sin.  And
> there's a lot of weird issues to resolve around what the syntax could even
> be, since PHP has untyped variables.
>
> The custom collection syntax Derick has been working on is a second-best
> alternative to generics, essentially.  It is less ergonomic, no question,
> but can also be implemented without generics, and so is about 5x easier to
> do.  If we could get native generics, then I think everyone involved agrees
> building collections off of that -- in essentially the same way as every
> language I mentioned above --- would be preferable to a custom one-off
> syntax.
>
> --Larry Garfield
>

Considering other languages it is worth mentioning that Java and C# have
generics AND typed arrays that act as a typed list/seq so sure it doesn't
solve all problems otherwise these languages wouldn't have both of them.

>From my personal experience, a typed list/seq solves most cases where I
need the elements of an array to be strictly instances of a specific type.
What I see typed list/seq like `string[]` has more ergonomics, it can be
used to interact between libraries and application code without creating
intermediate objects, while collection proposal always requires
declaring type - this simply multiplies the number of declared types and
create more coupling where it is not needed! Also, most cases I work with
are just fine with using just foreach or array_ family functions.

I believe typed list/seq could also be used to implement custom collection
like:

class Article {
function __construct(public string $title) {}
}

// collection(Seq) Articles {
// }

final class Articles {
public function __construct(protected Article[] $articles = []) {}
public function getIterator(): Traversable {
return new ArrayIterator($this->articles);
}
} // or extend any other collection class with just typed list/seq property

This doesn't have to collide with generics in any way, as mentioned before
in the thread these features may exist simultaneously, typed list/seq can
translate in the future to a generic type.
I believe it'd make people's lives easier if we could have this in place
soon.
Don't you agree?

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [Initial Feedback] Typed Arrays

2024-06-30 Thread Michał Marcin Brzuchalski
Hi Richard,

czw., 27 cze 2024, 22:33 użytkownik Richard Miles 
napisał:

>
> > I worked with Joe Watkins to do a proof-of-concept for generic traits.
> > It's a bit old since it's from 2017, but could be a useful starting
> > point if you are serious about pursuing this idea:
> >
> >
> https://github.com/php/php-src/compare/master...morrisonlevi:php-src:parameterized_traits
>
>
> I’m also interested in this; it will help see branches like these.
> Did you ever get the POC working? What did you feel like was the biggest
> hurdle?
>

There even was an RFC in voting which Joe implemented and it addresses
nearly what is discussed it this thread https://wiki.php.net/rfc/arrayof

I must admit that the collection proposal is bit too complex to
address such tiny but powerfully in my opinion functionality which is typed
array. What Derick showed looks more like generic collection and such
require declaring it's type. In my opinion this is way too mush hassle to
declare as many collection types as many usages in application. Also two
collection types with the same collection item type will not be compatible
from type perspective. While typed array seems much more clear and
compatible in all places where typed array is needed without declaring
separate type for each usage.

If I were to choose between typed-array and collection like Derick showed a
little bit I'd choose typed arrays definitely as a first feature to be
merged into PHP.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] [RFC] Static Constructor

2024-06-19 Thread Michał Marcin Brzuchalski
Hi Erick,

śr., 19 cze 2024 o 14:35 Erick de Azevedo Lima 
napisał(a):

> Hello everybody.
>
> I found myself wanting this feature (that I first encountered when
> programming in C#) for removing a workaround from a codebase I work from
> time to time.
> I searched internals and found a discussion from almost a decade ago. That
> discussion did not end well, mostly because of insulting accusations.
> I then decided to do some research on this subject and found out that it's
> a pretty common feature in other OOP languages.
> Also, as I started studying the php-src  (and missed the days when I used
> to program in C in my main job), I decided to do an implementation myself
> even before presenting the RFC.
> The implementation link can also be found at the RFC.
>
> You can read the RFC here:
> https://wiki.php.net/rfc/static_constructor
>
> Regards,
>
> Erick
>

I like the idea of having a static initializer.
I think we could propose a better naming, method name `function
__staticConstructor` is a concatenation of the words static and constructor
while constructor is used as an initializer when building constructing
objects.
Have you considered naming it for example shortly `function __static()` ?
It is somehow similar to https://wiki.php.net/rfc/static_constructor#java
in static-block.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Renaming "strict types" to "scalar type coercion"

2024-06-19 Thread Michał Marcin Brzuchalski
Hi David, Robert,

wt., 18 cze 2024 o 23:12 David Gebler  napisał(a):

> ...
> If I were to support any change to how this feature works for PHP 9, I
> think it would be providing a mechanism to enable it for all files at once,
> maybe either via a .ini setting such as strict_types_default=1 or a new
> declare which applies to all files included or autoloaded from that point
> on, i.e. a declare that could be used as the first line of an entrypoint
> script to make all files in a project have strict typing mode
> enabled/disabled (unless a particular file overrides for its own scope with
> its own declare).
>
> Changing the name to anything other than what it is now, with or without
> flipping the value, just seems like a major BC headache for no gain.
>

I share a similar opinion here.
I'd also rather see a proposal that enables setting the declares outside of
PHP files as this is mostly the same line for every file in most codebases
I work with.

# name it `.phpdeclare` in the execution directory or places where certain
PHP files are read by the PHP interpreter, whatever
```ini
# Global default directives
[*.php]
strict_types = 1
ticks = 0
encoding = UTF-8

# Directives for specific directories
[src/*.php]
strict_types = 1

[tests/*.php]
strict_types = 0

# Directives for specific files
[scripts/setup.php]
strict_types = 1
ticks = 1
```

Just an example, shoving some declares can be set using glob-like patterns
or specific files.
I see potential in this kind of declaring these directives for future
extensions.
This is something I'd love to consider instead of just renaming things we
already have.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Lazy Objects

2024-06-05 Thread Michał Marcin Brzuchalski
Hi Arnaud,

śr., 5 cze 2024 o 20:08 Arnaud Le Blanc  napisał(a):

> Hi Larry,
>
> Thank you for the feedback.
>
> I think you got the two strategies right. However, there is a use-case
> in which an object manages its own laziness by making itself lazy:
>
> ```
> class C {
>  public function __construct() {
> ReflectionLazyObject::makeLazyGhost($this, $this->init(...));
> }
> }
> ```
>
> This one can not be addressed by a newInstance*() method since the
> object to be made lazy already exists.
>

Did you consider implementing it using some attribute?

On constructor like:
```
class C {
#[LazyInitialization]
 public function __construct(private readonly string $foo) {
// ... init executes after first use, but all promoted properties
are already initialized
}
}
```

or on specialized initializer:

```
class C {
 public function __construct(private readonly string $foo) {
// do something light
}

#[LazyInitialization]
private function initi(): void
{
// do something heavy
}
}
```

I don't know if this is a good example of doing the same thing or if it
doesn't limit functionality,
but for me, it is way more clean and easier to understand.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC[ Property accessor hooks, take 2

2024-03-11 Thread Michał Marcin Brzuchalski
pon., 11 mar 2024 o 15:30 Larry Garfield 
napisał(a):

> On Mon, Mar 11, 2024, at 8:35 AM, Michał Marcin Brzuchalski wrote:
> > Hi Larry,
> >
> > pt., 8 mar 2024 o 16:55 Larry Garfield 
> napisał(a):
> >> Hi folks.  Based on earlier discussions, we've made a number of changes
> to the RFC that should address some of the concerns people raised.  We also
> had some very fruitful discussions off-list with several developers from
> the Foundation, which led to what we feel are some solid improvements.
> >>
> >> https://wiki.php.net/rfc/property-hooks
> >>
> >
> > This RFC looks awesome, thanks Larry and Ilija I love the functionality
> > in its current shape.
> >
> >> Thank you everyone for the feedback so far, and if you still have some,
> please say so.  (Even if it's just to say that you're happy with the RFC
> now so we feel more comfortable bringing it to a vote.)
> >
> > The only thing I don't like and can still be worked on is the
> > reflection mechanism changes.
> > The proposed methods isVirtual and getRawValue, setRawValue pair
> > introduces a need to catch exceptions which could be eliminated by
> > subtyping ReflectionProperty.
> > Having these methods on a separate subtype allows returning a valid
> > value.
> > I realize this isn't trivial because for the last 2 days, I was
> > thinking about giving it a name and TBH cannot figure out anything
> > feasible.
> > If this is not possible to put in understandable words then at least
> > mention it in FAQ and why not.
> >
> > Cheers,
> > Michał Marcin Brzuchalski
>
> Hm, interesting.  I'll have to check with Ilija on feasibility.  My
> question is, how would it eliminate it?
>
> Suppose we hypothetically have a "ReflectionPropertyWithHooks" reflection
> object.  It has those three extra methods on it.  But that means
> $rObject->getProperty() could return a ReflectionProperty or
> ReflectionPropertyWithHooks, and you don't know which it is.  You'd have to
> do an instanceof check to know which type of property it is, and thus what
> methods are available.  That doesn't seem any less clumsy (nor more, to be
> fair) than calling isVirtual().


It is similar when you work with ReflectionType or ReflectionEnum, you
always need to match against a certain type to ensure the code will behave
predictably.


> $rProp = $rObject->getProperty('foo', $obj);
> $rProp->getValue(); // works always.
>
> if (!$rProp->isVirtual()) {
> $rProp->getRawValue(); // Works, may or may not be the same return as
> getValue()
> }
>
> vs.
>
> if (!$rProp instanceof VirtualProperty) {
>   $rProp->getRawValue(); // Works.
> }
>
> That doesn't seem to be an improvement.  If you omit the conditional, you
> still need a catch one way or the other.  It just changes what gets thrown
> (an Exception vs an Error).  What type of hierarchy were you thinking of
> that would help here?
>

My thinking was like:
1. if the property has hooks, only then calling getRawValue, setRawValue,
or isVirtual make sense,
2. if the property has no hooks and is static calling getRawValue, or
setRawValue always throws because of "On a static property, this method
will always throw an error."
3. if the property is "virtual", calling getRawValue, or setRawValue always
throws an error,
4. if the property is not "virtual", calling getValue, or setValue is safe
and never throws, otherwise it may throw under some conditions related to
certain hook presence.

In conclusion, I thought that the presence of hooks introduces 3 new
methods but some will always be thrown because of incorrect usage.
Normally, I'd model it with subtypes to completely avoid try-catch blocks
for the cost of a simple instanceof check which I consider much cleaner for
the reader than a bunch of try-catch blocks. Remember about static
analysis, each of them when checked will propose to handle possible
exceptions.

But as wrote before, I don't know how to model it well.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC[ Property accessor hooks, take 2

2024-03-11 Thread Michał Marcin Brzuchalski
Hi Larry,

pt., 8 mar 2024 o 16:55 Larry Garfield  napisał(a):

> Hi folks.  Based on earlier discussions, we've made a number of changes to
> the RFC that should address some of the concerns people raised.  We also
> had some very fruitful discussions off-list with several developers from
> the Foundation, which led to what we feel are some solid improvements.
>
> https://wiki.php.net/rfc/property-hooks
>
>
This RFC looks awesome, thanks Larry and Ilija I love the functionality in
its current shape.

Thank you everyone for the feedback so far, and if you still have some,
> please say so.  (Even if it's just to say that you're happy with the RFC
> now so we feel more comfortable bringing it to a vote.)
>

The only thing I don't like and can still be worked on is the reflection
mechanism changes.
The proposed methods isVirtual and getRawValue, setRawValue pair introduces
a need to catch exceptions which could be eliminated by subtyping
ReflectionProperty.
Having these methods on a separate subtype allows returning a valid value.
I realize this isn't trivial because for the last 2 days, I was thinking
about giving it a name and TBH cannot figure out anything feasible.
If this is not possible to put in understandable words then at least
mention it in FAQ and why not.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Why are serialized strings wrapped in double quotes? (s::"")

2024-02-08 Thread Michał Marcin Brzuchalski
czw., 8 lut 2024 o 20:10 Sanford Whiteman 
napisał(a):

> Hi Michał,
>
> Thursday, February 8, 2024, 2:58:52 AM, you wrote:
> ...
> >O3:Foo:5{s4:date;O17:DateTimeImmutable:3{s4:date;s26:2024-02-08
>
> >08:41:10.009742;s13:timezone_type;i:3;s8:timezone;s16:Europe/Amsterdam}s6:*foo;s11:Foo
> >bar
>
> >baz;s8:Foobar;i:123456789;s3:tbl;a4{i:0;i:123;i:1;b:1;i:2;d:1.1;i:3;s3:baz}s8:*color;E12:Color:Yellow}
> >
> >This is still readable by humans and keep the size/length in all places
> >where needed.
>
> Amazing. To my eyes it's more readable too.
>

Just wondering, while null is encoded just as N the booleans are encoded
with b:0 or b:1
I can imagine this could also be just T and F


> Here's another one: leading numeral *implies* Integer 'i' (so only
> 'd', 'b' and 's' are necessary). Or maybe that goes too far.


I was there in the very first link you can spot it but also believe this
goes too far.

All above already goes far beyond what you initially asked and I know that.
I just like to share what can find.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Why are serialized strings wrapped in double quotes? (s::"")

2024-02-07 Thread Michał Marcin Brzuchalski
Hi Sandy,

wt., 6 lut 2024 o 21:19 Sanford Whiteman 
napisał(a):

> Howdy all, haven't posted in ages but good to see the list going strong.
>
> I'd like a little background on something we've long accepted: why
> does the serialization format need double quotes around a string, even
> though the byte length is explicit?
>
> Example:
>
>   s:5:"hello";
>
> All else being equal I would think we could have just
>
>   s:5:hello;
>
> and skip forward 5 bytes. Instead we need to be aware of the leading
> and trailing " in our state machine but I'm not sure what the
> advantage is.
>

You inspired me to play with serialization format to spot even more
unnecessary chars https://3v4l.org/DLh1U
>From my PoV there are more candidates to reduce and still keep the safety,
for eg:
removing leading ':' before array/object and trailing ';' inside brackets,
you reduce by 2 bytes

a:4:{i:0;i:123;i:1;b:1;i:2;d:1.1;i:3;s:3:"baz";}

Could be simply

a:4{i:0;i:123;i:1;b:1;i:2;d:1.1;i:3;s:3:baz}

This example saves 4 bytes: double-quotes, one ; and :

If you go further all types that require size/length also don't need extra
double-colon meaning:
a:4 could become a4
s:3 could become s3

The same could apply to O: and E:

O3:Foo:5{s4:date;O17:DateTimeImmutable:3{s4:date;s26:2024-02-08
08:41:10.009742;s13:timezone_type;i:3;s8:timezone;s16:Europe/Amsterdam}s6:*foo;s11:Foo
bar
baz;s8:Foobar;i:123456789;s3:tbl;a4{i:0;i:123;i:1;b:1;i:2;d:1.1;i:3;s3:baz}s8:*color;E12:Color:Yellow}

This is still readable by humans and keep the size/length in all places
where needed.
My attached example is poor but shows up to ~20% size reduction.

Interestingly when an array is serialized as object property it is not
followed by ; in field list https://3v4l.org/4p6ve

O:3:"Foo":2:{s:3:"foo";a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}s:3:"bar";s:3:"baz";}

Missing ; between }s was a surprise to me.

Best regards,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC proposal: worker mode primitives for SAPIs

2024-01-05 Thread Michał Marcin Brzuchalski
pt., 5 sty 2024 o 13:19 Robert Landers 
napisał(a):

> On Fri, Jan 5, 2024 at 11:59 AM Rowan Tommins 
> wrote:
>
> > > Globals is how this works (atm)
> >
> > It's how it works for native SAPIs. It's not, as far as I know, how any
> worker system other than FrankenPHP has implemented its API. Every other
> implementation I've seen, whether async or not, passes in some form of
> request data to the callback, with the exception of RoadRunner, which gives
> the data as a return value from a "get next request" function.
>
> Nearly every library in existence knows how to use these globals
> (including 30 years old legacy code). There are also the unwieldy PSR
> request/response containers for which there are dozens (if not
> hundreds) of implementations. It would be fantastic if there were
> already an extension-based implementation that could be adopted into
> php-src; though I feel like that is a separate conversation.
>

There are indeed dozens of libraries already working with PSR nicely but
IMHO
the API should provide all the necessary information in a way that allows
the construction of such objects,
but suggesting PSR with request/response objects will limit the
capabilities of worker mode API
to handle pure HTTP protocol only.

What I'd like to say is that I believe for the initial proposal of any
eventual worker mode API
with the PSR with request/response objects should not be considered at all.

Cheers


Re: [PHP-DEV] [RFC] Add http_(get|clear)_last_request_headers() function

2024-01-03 Thread Michał Marcin Brzuchalski
śr., 3 sty 2024 o 15:57 Gina P. Banyard  napisał(a):

> On Wednesday, 3 January 2024 at 14:38, Michał Marcin Brzuchalski <
> michal.brzuchal...@gmail.com> wrote:
>
> Hi Gina,
>
> śr., 3 sty 2024 o 14:41 Gina P. Banyard  napisał(a):
>
> Hello internals,
>
> I would like to propose an RFC to add the functions
> http_get_last_request_headers() and http_clear_last_request_headers() to
> PHP to replace the magic variable $http_response_header.
>
> Link: https://wiki.php.net/rfc/http-last-response-headers
>
>
> I was on the specific documentation page describing this feature Today and
> was thinking that it is inappropriate as well.
> But my thinking was whether it shouldn't be a part of a stream context
> instead, something like this:
>
> $response_headers;
> $context = stream_context_create([
> 'http' => ['response_headers' => &$response_headers]
> ]);
> $result = file_get_contents('http://example.com/submit.php', false,
> $context);
>
> This way by ref you get a specific HTTP wrapper running under the hood
> response headers instead of just the last one.
> Any thoughts about that?
>
>
> I don't understand why the response should be part of the context of a
> stream.
> Especially as I'm not aware of anything within the context that changes
> values after a request?
>

My thinking was like passing as part of the context a placeholder by ref
where the headers of requests done in this context are to be populated.
This means instead of calling http_get_last_request_headers() as you
propose just read them from $response_headers array which got populated
during the HTTP call.
In general the same to what Aleksander asked.

Cheers


Re: [PHP-DEV] [RFC] Add http_(get|clear)_last_request_headers() function

2024-01-03 Thread Michał Marcin Brzuchalski
Hi Gina,

śr., 3 sty 2024 o 14:41 Gina P. Banyard  napisał(a):

> Hello internals,
>
> I would like to propose an RFC to add the functions
> http_get_last_request_headers() and http_clear_last_request_headers() to
> PHP to replace the magic variable $http_response_header.
>
> Link: https://wiki.php.net/rfc/http-last-response-headers


I was on the specific documentation page describing this feature Today and
was thinking that it is inappropriate as well.
But my thinking was whether it shouldn't be a part of a stream context
instead, something like this:

$response_headers;
$context = stream_context_create([
'http' => ['response_headers'  => &$response_headers]
]);
$result = file_get_contents('http://example.com/submit.php', false,
$context);

This way by ref you get a specific HTTP wrapper running under the hood
response headers instead of just the last one.
Any thoughts about that?

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC][Discussion] NotSerializable attribute

2024-01-03 Thread Michał Marcin Brzuchalski
śr., 3 sty 2024 o 11:10 Nicolas Grekas 
napisał(a):

>
 śr., 3 sty 2024 o 08:12 Nicolas Grekas 
 napisał(a):

> Hi Max,
>
> Hi, I'd like to propose a new attribute, #[NotSerializable]. This
> > functionality is already available for internal classes - userspace
> should
> > benefit from it, too.
> >
> > The RFC: https://wiki.php.net/rfc/not_serializable
> > Proposed implementation: https://github.com/php/php-src/pull/12788
> >
> > Please let me know what you think.
> >
>
> Regarding the inheritance-related behavior ("The non-serializable flag
> is
> inherited by descendants"), this is very unlike any other attributes,
> and
> this actively prevents writing a child class that'd make a parent
> serializable if it wants to.
>
> To me, if this is really the behavior we want, then the attribute
> should be
> replaced by a maker interface.
> Then, a simple "instanceof NotSerializable" would be enough instead of
> adding yet another method to ReflectionClass.
>

 This should be possible without ReflectionClass, see
 https://3v4l.org/N3fmO

>>>
>>> Sure.
>>>
>>> My main point is : why use an attribute? this should be an interface to
>>> me. All semantics match an interface.
>>>
>>>
 From the serialization libraries you can find similar attributes

>>>
>>> Those a very different, because they tackle the problem from the
>>> *external* angle: the attributes there describe how a system *external* to
>>> the class itself should best serialize an object. There, attributes make
>>> sense, because they enrich the description of the class without forcibly
>>> telling what to do with the object
>>>
>>> But in the RFC, we're talking about the object deciding itself how it
>>> should be (not) serialized. This is enforced and thus belongs to the
>>> typesystem - not to an attribute.
>>>
>>
>> But then what should implement the NotSerializable interface?
>> If you want to ignore a string-typed property there would be no option to
>> mark it with a NotSerializable interface
>> Consider "baz" property in this example:
>>
>> class Foo {
>> protected int $bar = 1;
>> #[NotSerializable]
>> protected string $baz = 2;
>> }
>>
>
>
> The attribute is #[Attribute(Attribute::TARGET_CLASS] so I'm not sure why
> you consider this as it's not mentioned in the RFC (and I'm not sure it
> would make sense).
>

Apologies, apparently I didn't read.

Cheers


Re: [PHP-DEV] [RFC][Discussion] NotSerializable attribute

2024-01-03 Thread Michał Marcin Brzuchalski
śr., 3 sty 2024 o 10:09 Nicolas Grekas 
napisał(a):

> Hi Nicolas,
>>
>> śr., 3 sty 2024 o 08:12 Nicolas Grekas 
>> napisał(a):
>>
>>> Hi Max,
>>>
>>> Hi, I'd like to propose a new attribute, #[NotSerializable]. This
>>> > functionality is already available for internal classes - userspace
>>> should
>>> > benefit from it, too.
>>> >
>>> > The RFC: https://wiki.php.net/rfc/not_serializable
>>> > Proposed implementation: https://github.com/php/php-src/pull/12788
>>> >
>>> > Please let me know what you think.
>>> >
>>>
>>> Regarding the inheritance-related behavior ("The non-serializable flag is
>>> inherited by descendants"), this is very unlike any other attributes, and
>>> this actively prevents writing a child class that'd make a parent
>>> serializable if it wants to.
>>>
>>> To me, if this is really the behavior we want, then the attribute should
>>> be
>>> replaced by a maker interface.
>>> Then, a simple "instanceof NotSerializable" would be enough instead of
>>> adding yet another method to ReflectionClass.
>>>
>>
>> This should be possible without ReflectionClass, see
>> https://3v4l.org/N3fmO
>>
>
> Sure.
>
> My main point is : why use an attribute? this should be an interface to
> me. All semantics match an interface.
>
>
>> From the serialization libraries you can find similar attributes
>>
>
> Those a very different, because they tackle the problem from the
> *external* angle: the attributes there describe how a system *external* to
> the class itself should best serialize an object. There, attributes make
> sense, because they enrich the description of the class without forcibly
> telling what to do with the object
>
> But in the RFC, we're talking about the object deciding itself how it
> should be (not) serialized. This is enforced and thus belongs to the
> typesystem - not to an attribute.
>

But then what should implement the NotSerializable interface?
If you want to ignore a string-typed property there would be no option to
mark it with a NotSerializable interface
Consider "baz" property in this example:

class Foo {
protected int $bar = 1;
#[NotSerializable]
protected string $baz = 2;
}

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC][Discussion] NotSerializable attribute

2024-01-03 Thread Michał Marcin Brzuchalski
Hi Nicolas,

śr., 3 sty 2024 o 08:12 Nicolas Grekas 
napisał(a):

> Hi Max,
>
> Hi, I'd like to propose a new attribute, #[NotSerializable]. This
> > functionality is already available for internal classes - userspace
> should
> > benefit from it, too.
> >
> > The RFC: https://wiki.php.net/rfc/not_serializable
> > Proposed implementation: https://github.com/php/php-src/pull/12788
> >
> > Please let me know what you think.
> >
>
> Regarding the inheritance-related behavior ("The non-serializable flag is
> inherited by descendants"), this is very unlike any other attributes, and
> this actively prevents writing a child class that'd make a parent
> serializable if it wants to.
>
> To me, if this is really the behavior we want, then the attribute should be
> replaced by a maker interface.
> Then, a simple "instanceof NotSerializable" would be enough instead of
> adding yet another method to ReflectionClass.
>

This should be possible without ReflectionClass, see https://3v4l.org/N3fmO
A property redeclare doesn't inherit the attributes, therefore this might
be a solution for the problem you presented.
Another ad-hoc way could be implementing `__serialize()` in the child class.

I like this feature and the only thing I'd like to consider is different
naming options for voting.

>From the serialization libraries you can find similar attributes, these are:
* https://github.com/Crell/Serde `#[Crell\Serde\Attributes\Field(exclude:
true)]`
* https://github.com/symfony/serializer
`#[Symfony\Component\Serializer\Attribute\Ignore]`
* https://github.com/schmittjoh/serializer
`#[JMS\Serializer\Annotation\Exclude]`

In the Java world also:
* Java EE or Jakarta EE and using JAX-RS `@Transient`
* Jackson `@JsonIgnore`

In the C# world
* .NET _System.Text.Json.Serialization_ `[JsonIgnore]`

So there might be some other naming proposals like maybe just `Ignore` or
`Exclude` ?

What is worth mentioning are solutions allowing to change the strategy on
inheritance which JMS/Serializer supports
https://jmsyst.com/libs/serializer/master/reference/annotations#exclusionpolicy

The `#[ExclusionPolicy]` allows to declare that all properties should be
excluded or none.

Worth mentioning a future scope could introduce more interesting solutions
like:
* Exclude/Ignore conditionally on class or property level, for eg:
  a. if the value is null,
  b. or is undefined or
  c. its value is the default value - which allows to skip serialization of
properties with default values that will be unserialized back with the
default value - see https://3v4l.org/6b1Y6

Similar solutions used by:
* JMS/Serializer `#[JMS\Serializer\Annotation\SkipWhenEmpty]
* .NET `[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]`
see
https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignorecondition?view=net-8.0

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC proposal: worker mode primitives for SAPIs

2023-12-30 Thread Michał Marcin Brzuchalski
Hi Larry,

sob., 30 gru 2023 o 20:49 Larry Garfield 
napisał(a):

> On Sat, Dec 30, 2023, at 4:53 AM, Rowan Tommins wrote:
> > On 30 December 2023 09:59:07 GMT, Robert Landers
> >  wrote:
> >>For this to happen in PHP Core, there would need to be request objects
> >>instead of a global state.
> >
> > Again, the representation as objects isn't a key requirement. Python's
> > WSGI spec simply has a dictionary (read: associative array) of the
> > environment based on CGI. The application might well turn that into a
> > more powerful object, but standardisation of such wasn't considered a
> > pre-requisite, and would actually have hampered ASGI, where not all
> > events represent an HTTP request.
> >
> > The key requirement is that you have some way of passing the current
> > request and response around as scoped variables, not global state.
> > That's essential for any kind of concurrent run-time (async,
> > thread-aware, etc).
> >
> > An event / subscriber model fits well with that: the local scope for
> > each request is set up by an invocation of the callback with defined
> > parameters and return value.
> >
> > Funnily enough, the example of a worker script for FrankenPHP does both
> > things: it sends each request to the same application "handle"
> > callback, passing in the super-global arrays as parameters to be used
> > as non-global state. https://frankenphp.dev/docs/worker/#custom-apps So
> > really all I'm arguing is that a few more lines of that PHP example be
> > moved into the C implementation, so that the user only needs to provide
> > that inner callable, not the outer while loop.
>
> So you're suggesting something like:
>
> $app->initializeStuffHowever();
> set_event_handler(Closure $handler);
> // Script blocks here until a sigkill is received, or something.
>
> I think there's an important distinction that is getting missed in the
> above discussion, beyond the push-vs-pull question.  FrankenPHP, as I
> understand it, pre-boots multiple worker processes, keeps them in memory,
> and then handles each request in its own process.  Swoole,
> Amp/React/Revolt, and friends have only a single process running at all,
> and make use of async to simulate multiple simultaneous requests, a la
> NodeJs.  That means mutable global variables in the FrankenPHP model still
> won't leak between parallel requests, whereas they absolutely would/do in a
> Swole/Revolt world.
>
> I'm not going to call one of those better or worse (I don't have enough
> experience with either to say), but they are different beasts for which
> first class support would be different SAPIs either way.  They're not
> mutually exclusive thanks to Fibers (which mean you don't need the entire
> call stack to be async), but you would want to pick one or the other as
> primary runner mode of an application.  Let's keep that in mind when making
> comparisons.
>
> The Franken-model is closer to how PHP-FPM works today, which means that
> is easier to port existing code to, especially existing code that has lots
> of globals or hidden globals.  (Eg, Laravel.)  That may or may not make it
> the better model overall, I don't know, but it's the more-similar model.
>
> All that said, the idea of allowing a "persistent HTTP handler process"
> SAPI, "persistent Queue handler process" SAPI, and "persistent cron handler
> process" SAPI (or whatever combination of persistent processes) to all run
> side by side with the same code base but different entry point scripts
> is...  Hot.  If we can do something that would enable that kind of runtime
> model, I am very much here for that.
>

What you wrote sounds like some good points (as usual).
I'm not an expert (yet!) but was playing around with some callable trying
to mimic ASGI
https://github.com/brzuchal/asgi-playground/blob/main/app.php#L26-L37

What I think currently (maybe too hurry, but...) is that this kind of
approach is flexible enough to handle in easy way many SAPIs which identify
to app their capabilities,
and the app decides how and what can handle `$scope['type']` in the example
code.

I know there is a Runtime library, that tries to integrate
Symfony/Laaravel to many SAPIs, but as far as I understood the discussion
went to figure out if there is some kind of standard approach that could be
shaped under the PHP umbrella.

Maybe this is just a temporary fascination about ASGI solution, could be.
If this is not in the scope of interest of anyone then forgive me, I won't
bother anymore.

Cheers,
--
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC proposal: worker mode primitives for SAPIs

2023-12-30 Thread Michał Marcin Brzuchalski
Hi Robert,

sob., 30 gru 2023, 10:59 użytkownik Robert Landers 
napisał:

> > > - FrankenPHP expects the user to manage the main event loop ...
> > >
> > >
> > > This isn't exact. FrankenPHP does manage the event loop (the Go
> > > runtime manages it - through a channel - under the hood).
> >
> >
> > Perhaps "event loop" was the wrong term; what I was highlighting is that
> > to use FrankenPHP or RoadRunner, you have to write a while loop, which
> > explicitly handles one request at a time. In Swoole, there is no such
> > loop: you register event handlers and then call $server->run() once.
> > Similarly, WSGI mandates that the server "invokes the application
> > callable once for each request it receives from an HTTP client".
> >
> > It's a distinction of pull/poll (the application must actively block
> > until next request) vs push/subscribe (the application is passively
> > invoked whenever needed).
>
> I think these models have different capabilities: A pull/poll model is
> quite simple, while a subscription model is usually more complex.
>
> With something simple like in FrankenPHP, creating a Queue SAPI, a
> WebSocket SAPI, etc isn't far off, where someone writes some PHP to
> consume a queue or websocket connections.
>
> > > I already replied to Crell about that. It will totally possible to
> > > expose more complex HTTP message objects in the future,
> > > but PHP currently lacks such objects. The only things we have are
> > > superglobals (which are more or less similar to CGI variables, as done
> > > in WSGI) and streams. It's why we're using them.
> >
> >
> > The use of objects vs arrays wasn't the main difference I was trying to
> > highlight there, but rather the overall API of how information gets into
> > and out of the application. FrankenPHP is the only server listed which
> > needs to reset global state on each request, because the others
> > (including Python WSGI and ASGI) use non-global variables for both input
> > and output.
> >
> > I notice that the Laravel Octane adaptor for FrankenPHP takes that
> > global state and immediately converts it into non-global variables for
> > consumption by the application.
>
> For this to happen in PHP Core, there would need to be request objects
> instead of a global state. If an RFC implementing PSR
> requests/responses in Core is a pre-requisite for enabling what we're
> discussing here, I'd personally be all for that (as would a very large
> chunk of the PHP community, IMHO). I personally think this is a
> chicken/egg type of problem though. It doesn't make sense to have
> request/response objects right now, and I get the feeling that people
> would only support worker mode primitives if there were request
> objects... so, it might make sense to build a v1 of the worker mode
> primitives and then iterate towards request objects, because then
> there would be an actual need for them.
>

That is certainly not true. Looking at WSGI or ASGI there is no need for
request response objects. These can be provided in userland which gives
more flexibility cause of different rules governing over bc break policy in
PHP core.

Name one true argument to convince me in this topic and I may change my
mind.
For the years I had the same impression but on low level the primitives are
more flexible and we all know that.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] RFC proposal: worker mode primitives for SAPIs

2023-12-30 Thread Michał Marcin Brzuchalski
Hi Rowan,

pt., 29 gru 2023 o 23:56 Rowan Tommins  napisał(a):

> On 29/12/2023 21:14, Kévin Dunglas wrote:
> ...
> The use of objects vs arrays wasn't the main difference I was trying to
> highlight there, but rather the overall API of how information gets into
> and out of the application. FrankenPHP is the only server listed which
> needs to reset global state on each request, because the others
> (including Python WSGI and ASGI) use non-global variables for both input
> and output.
>

I wasn't aware of ASGI, in the past I read about WSGI and noticed a PHP
connector allowing the PHP app to run inside the WSGI server.
I read most of the spec
https://asgi.readthedocs.io/en/latest/specs/index.html yesterday and it
sounds like a really solid solution.
Personally, I'd love to see something similar for PHP.
It'd clearly be something different from the usual PHP app where global
$_GET|POST variables carry the HTTP request input.
Solution taken by Python in fact is about returning a callable fulfilling a
specific signature no matter if this is a simple function, closure or
Object implementing __invoke function - and this gives much flexibility.
I believe that considering the fact that ASGI provides an API for HTTP
interaction including WebSockets that could only benefit to PHP ecosystem.

In the past, I was thinking about something similar to adopting WSGI but
was not aware of ASGI.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Is it possible to add asynchronous loop call function ?

2023-11-24 Thread Michał Marcin Brzuchalski
Hi Robert,

pt., 24 lis 2023 o 10:24 Robert Landers 
napisał(a):

> ...
> You can also emulate this with:
>
> class Defer {
>   private function __construct(private \Closure $callback) {}
>   public function __destruct() { $this->callback(); }
>   public static function _(\Closure $callback) { return new
> self($callback); }
> }
>
> and use it like:
>
> function writeSomeStuff() {
>   // open files
>   $deferred = Defer::_($closeFiles(...));
>   // do stuff
> }
>
> So long as a reference exists to $deferred variable, the deferred
> method won't be run. If the variable is local to the method/function
> being run it, the deconstructor will be called after the function
> returns.
>
> It isn't the most beautiful thing in the world, and easy to forget to
> store the result of Defer, but it is handy sometimes.
>

This is interesting which makes me thinking if forget to store it could be
prevented.
I think requiring a ref could help with that:

class Defer {
  private function __construct(private \Closure $callback) {}
  public function __destruct() { ($this->callback)(); }
  public static function _(\Closure $callback, &$var) { $var = new
self($callback); }
}

$deferred = Defer::_($closeFiles(...), $foo);

Without $foo there'd be an ArgumentCountError.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Re: [RFC][Under discussion] RFC1867 for non-POST HTTP verbs

2023-10-13 Thread Michał Marcin Brzuchalski
Hi Ilija,

pt., 13 paź 2023, 13:15 użytkownik Ilija Tovilo 
napisał:

> Hi everyone
>
> On Fri, Oct 6, 2023 at 3:44 PM Ilija Tovilo 
> wrote:
> > https://wiki.php.net/rfc/rfc1867-non-post
>
> Thank you for the feedback so far. I made a handful of changes to the RFC.
>
> * The function is renamed to request_parse_body()
> * The function will now throw instead of emitting warnings when hitting
> limits
> * The Configuration section was added show how parsing limits may be
> modified per endpoint
> * The php://input is explained better in relation to multipart parsing
>
> Let me know if you have any more feedback.
>

Considering the function supports two formats multipart/form-data or
the application/x-www-form-urlencodedand
the fact that the return type and required arguments differ in regards to
format: content-type needed for multipart which returns two arrays packed
into return array aka $_POST and $_FILES and the boundary that is part of
content-type header and the other format that doesn't require content-type
header and returns effectively only one array aka $_POST why not having two
separate functions?

The proposal is to include two separate functions that have clear semantics
and prevent from invoking multipart without boundary or only form with
boundary:
* request_parse_body($input_stream): array - returning just $_POST
and maybe
* request_parse_multupart_body($input_stream, string $boundary): array
returning as proposed now two arrays packed $_POST and $_FILES

Why the $inpit_stream accepts null - does it make sense to invoke the
function then?


Re: [PHP-DEV] [RFC][Under discussion] RFC1867 for non-POST HTTP verbs

2023-10-06 Thread Michał Marcin Brzuchalski
Hi Marco,

sob., 7 paź 2023 o 00:55 Marco Aurélio Deleu 
napisał(a):

> Just wanted to mention that maybe this is a great opportunity to create a
> request_ family and start with request_parse_post_data
>

My first thought was why the word `_post_` and not for instance instead
a`_form_` which better expresses the purpose then?
I'd avoid using the "post" word if we tend to provide functionality that is
common for other HTTP methods which in fact was the preliminary cause of
this discussion.

Cheers,
Michał Marcin Brzuchalski


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

2023-07-11 Thread Michał Marcin Brzuchalski
Hi Robert,

wt., 11 lip 2023 o 14:54 Robert Landers 
napisał(a):

> ...
> Abstract classes solve this problem perfectly. It's part of the type
> system, it's type-hintable, it's mockable, and it's pretty easy to see
> what inherits it as people who inherit it already know what the base
> behavior was when they wrote the code.
>

Not exactly, How you wanna solve by abstract class two interfaces
which can be implemented using let's say two traits - let's say

interface Foo {
public function foo(): string;
}
trait HasFoo {
public function foo(): string { return 'foo'; }
}
interface Bar {
public function bar(): bool;
}
traitHasBar {
public function bar(): bool { return true; }
}

Now I can need to implement Foo or Bar separately or together.
Using abstract class that would require 3 abstract classes: Foo, Bar, and
FooWithBar.
With this RFC that would require just two interfaces with default methods.

Now you can easily see how bad this goes if you wanna add 3rd interface.

Cheers,
Michał Marcin Brzuchalski


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

2023-07-03 Thread Michał Marcin Brzuchalski
pon., 3 lip 2023 o 14:26 Andreas Heigl  napisał(a):

> Hey Michał
>
> On 03.07.23 13:32, Michał Marcin Brzuchalski wrote:
> > Hi Levi,
> >
> > pon., 3 lip 2023 o 02:11 Levi Morrison 
> napisał(a):
> >
> >> Chatter on the [Interface Default Methods RFC][1] has been quiet for
> >> the past 6 days, and the feature freeze deadline is fast approaching
> >> for PHP 8.3, so I'm moving this to vote. It'll be open for two weeks
> >> as usual.
> >>
> >> Thanks to everyone who discussed weaknesses in the RFC during the
> >> discussion phase.
> >>
> >>[1]: https://wiki.php.net/rfc/interface-default-methods
> >
> >
> > I voted "yes", my personal use case waits for this feature. My use
> > case example:
> >
> > https://gist.github.com/brzuchal/89e9481bbd34a6ce3d95a68eabff038b
>
> I've added two already possible solutions to that as comments.
> >
> > With interface default methods I'd no longer need traits that implement a
> > single or in rare cases 2 methods that
> > use their respective methods returning objects and iterate in Generator
> > fashion over a paginated result set.
> > This is not an issue if there is one implementation of the interface but
> > when I decorate to apply some:
> > * caching
> > * logging
> > * failover
>
> That requires that you are in control over both the interface AND the
> implementation. In which case you probably do not need an interface and
> the Trait would be enough (using `abstract public function` in traits
> works after all)
>
> So you could even skip the implements part.
>
> As the interface should be designed specifically to be
> implementation-agnostic, adding implementation to the interface is
> counter-productive.
>
> Adding abstract methods to a trait and then just adding the traits is no
> issue at all especially when you are in control of the interface AND the
> implementation.
>
> When you are NOT in control of the interface... well, you can't expect
> to have a default implementation and I am already looking forward to the
> complaints that it is great to have a default implementation, but not
> *that* one.
>
> There is a reason why the respective construct in Rust (which was
> mentioned in the RFC) is called a Trait and not an Interface.
>
> So to decouple the contract from the implementation it is necessary that
> no implementation is part of the contract.
>
> >
> > then the trait has to be attached to every class besides that it has to
> > exist which is an additional symbol here.
>
> Stop using `implements` at all and solely rely on `use`.
>

I use an interface for mocks in unit tests.
A default interface method allows me to remove some traits which are not my
favorite and I'd like to remove them all.
Turning the interface into an abstract class adds an inheritance that I
want to avoid.
Given that, it true is that it is possible to solve the problem differently
but not without side effects (either lack of contract or inheritance).

Cheers,
Michał Marcin Brzuchalski


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

2023-07-03 Thread Michał Marcin Brzuchalski
pon., 3 lip 2023 o 13:50 Pierre  napisał(a):

> Le 03/07/2023 à 13:32, Michał Marcin Brzuchalski a écrit :
> > I voted "yes", my personal use case waits for this feature. My use
> > case example:
> >
> > https://gist.github.com/brzuchal/89e9481bbd34a6ce3d95a68eabff038b
> >
> > With interface default methods I'd no longer need traits that implement a
> > single or in rare cases 2 methods that
> > use their respective methods returning objects and iterate in Generator
> > fashion over a paginated result set.
> > This is not an issue if there is one implementation of the interface but
> > when I decorate to apply some:
> > * caching
> > * logging
> > * failover
> >
> > then the trait has to be attached to every class besides that it has to
> > exist which is an additional symbol here.
> >
> > Cheers,
> > Michał Marcin Brzuchalski
>
> Please everyone yes to this !
>
> I use Symfony daily, and the SomethingAwareInterface /
> SomethingAwareTrait is very annoying, by having default method
> implementations on interfaces, it would remove the use of having traits
> at all. Everything would be much easier to read and write.
>

I agree, there are two interfaces that always require adding a trait in
Symfony.
These are NormalizerAwareInterface, DenormalizerAwareInterface
They always require including NormalizerAwareTrait, DenormalizerAwareTrait.

With this feature none of the above traits would no longer be required and
the interface use would be less confusing.

Cheers,
Michał Marcin Brzuchalski


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

2023-07-03 Thread Michał Marcin Brzuchalski
Hi Andreas,

pon., 3 lip 2023 o 06:33 Andreas Heigl  napisał(a):

> Am 03.07.23 um 02:11 schrieb Levi Morrison:
> > Chatter on the [Interface Default Methods RFC][1] has been quiet for
> > the past 6 days, and the feature freeze deadline is fast approaching
> > for PHP 8.3, so I'm moving this to vote. It'll be open for two weeks
> > as usual.
> >
> > Thanks to everyone who discussed weaknesses in the RFC during the
> > discussion phase.
> >
> >[1]: https://wiki.php.net/rfc/interface-default-methods
> >
> I've voted "no" on this RFC for one simple reason:
>
> For me an interface is about the abstraction of a contract. It defines
> how different parts of code interact with one another without having to
> know about the implementation.
>
> With this RFC we are adding implementation details to the abstraction.
>
> That requires knowledge about the implementation of different parts of
> the code. Which we do not have when defining an interface.


I disagree, look at the example I presented in my other response,
one method can use another to provide a default method which you'd be
including via trait
in every implementing class because as it only uses another interface
method.
This means that you don't need to know anything about the implementation
itself at all.
You're free to use other interface methods and don't need any properties or
implementation details.

Cheers,
Michał Marcin Brzuchalski


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

2023-07-03 Thread Michał Marcin Brzuchalski
Hi Levi,

pon., 3 lip 2023 o 02:11 Levi Morrison  napisał(a):

> Chatter on the [Interface Default Methods RFC][1] has been quiet for
> the past 6 days, and the feature freeze deadline is fast approaching
> for PHP 8.3, so I'm moving this to vote. It'll be open for two weeks
> as usual.
>
> Thanks to everyone who discussed weaknesses in the RFC during the
> discussion phase.
>
>   [1]: https://wiki.php.net/rfc/interface-default-methods


I voted "yes", my personal use case waits for this feature. My use
case example:

https://gist.github.com/brzuchal/89e9481bbd34a6ce3d95a68eabff038b

With interface default methods I'd no longer need traits that implement a
single or in rare cases 2 methods that
use their respective methods returning objects and iterate in Generator
fashion over a paginated result set.
This is not an issue if there is one implementation of the interface but
when I decorate to apply some:
* caching
* logging
* failover

then the trait has to be attached to every class besides that it has to
exist which is an additional symbol here.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC1867 (multipart/form-data) PUT requests

2023-06-27 Thread Michał Marcin Brzuchalski
Hi Andreas,

śr., 28 cze 2023 o 07:55 Andreas Heigl  napisał(a):

> ...
> While I like not adding more Superglobals, it seems like we are adding
> more and more functions to retrieve the different parts of a
> Request-Object...
>
> So when we are at it: Why don't we introduce exactly that? A
> Request-Object that has all the methods. And which is immutable.
>
> And one method `request(): \Request`
>

I agree with the above, this would allow us to clean up the global
namespace in the future.
My personal use cases for PHP are mostly queue workers/event stream
consumers,
so the usual request/response model SAPI is used rarely. But I understand
that it's not the most used case.
Adding a couple of additional functions to a set of already ones just adds
more symbols not always used.
Ideally, I'd see an HTTP module in the future enabled in
request/response-oriented SAPI but that's a different story.


>
> I deliberately didn't call it `getRequest` (or `get_request`) to not
> confuse people why there isn't also a `post_request` or `put_request` or
> ... you get the picture)
>
> One additional function in global namespace and then we can use one of
> the request-objects that are already out in the wild. I don't think
> there's a need to invent the wheel again.
>
> The advantage might be that no matter how many calls to `request()` you
> will always get the same result. The Request as it came in.
>

That sounds like a use for a const?!

Just my .50€

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Clone with

2023-05-29 Thread Michał Marcin Brzuchalski
Hi Máté,

pon., 29 maj 2023 o 11:18 Máté Kocsis  napisał(a):

> Hi Everyone,
>
> In the meanwhile, I changed my proposal to use [] instead of {} after the
> "with" clause due to its better receptance.
> Additionally, I removed support for the shorthand "property assignment"
> syntax (clone $this with [property1: "foo"]) in
> favor the more powerful one where the left-hand side supports expressions
> (clone $this with ["property1" => "foo"])
> so that we have more time to decide whether the former one is really
> needed.
>

So there would be no option to vote on shorthand properties, right?

Array syntax with all properties as strings in quotes probably means no
support from IDE.
I think this is a really bad move, I'd be against it.

Cheers,
Michał Macin Brzuchalski


Re: [PHP-DEV] [RFC] Property hooks, nee accessors

2023-05-09 Thread Michał Marcin Brzuchalski
Hi Larry,

pon., 8 maj 2023 o 23:38 Larry Garfield  napisał(a):

> Ilija Tovilo and I would like to offer another RFC for your
> consideration.  It's been a while in coming, and we've evolved the design
> quite a bit just in the last week so if you saw an earlier draft of it in
> the past few months, I would encourage you to read it over again to make
> sure we're all on the same page.  I'm actually pretty happy with where it
> ended up, even if it's not the original design.  This approach eliminates
> several hard-to-implement edge cases while still providing a lot of
> functionality in one package.
>
> https://wiki.php.net/rfc/property-hooks


> Using $this->propertyName directly is supported, but not recommended.
Why is that? IMHO in the scope of accessor this is much clearer to me than
using the $field.

> The following example does make use of $field, however, and thus a
backing value will be created, and write operations will simply write to
the property as normal.
This looks like new magic to me, whether we allow setting and baking the
value explicitly or not. I consider this behavior confusing.

Overall I vote yes.
Cheers,
Michał Marcin Brzuchalski


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

2023-04-25 Thread Michał Marcin Brzuchalski
Hi Nicolas,

wt., 25 kwi 2023, 19:00 użytkownik Nicolas Grekas <
nicolas.grekas+...@gmail.com> napisał:

> Hi all,
>
>
> https://wiki.php.net/rfc/allow_casting_closures_into_single-method_interface_implementations
> >
> >
> https://wiki.php.net/rfc/allow-closures-to-declare-interfaces-they-implement
> > https://wiki.php.net/rfc/structural-typing-for-closures
>
>
> Thanks Larry for the nice introduction to those ideas.
>
> Personally, I feel like going with adding Closure::castTo() might provide
> the most immediate benefit. I expanded the rationale on the corresponding
> RFC and added more examples. I'd appreciate it if all of you reading could
> have another look to see if that helps to better understand the proposal.
>
> strtr(...)->castTo(TranslatableInterface::class) is one example of RFC #1
> function ($message, $parameters) implements TranslatableInterface is RFC #2
>
> Both RFCs nicely combine together to cover many cases of typed callabled.
>
> Then RFC#3 is a bit more adventurous (according to our understanding) but
> still desirable as it's essentially about allowing the engine to
> tentatively call castTo() from RFC#1 when a closure is passed as argument
> while an interface is expected.
>

Personally I don't like this way of shaping callable types. Given examples
are really confusing me. Call of a castTo() with argument representing an
interface with a method is confusing as the method magically appears on a
closure without explicit binding to it! What if an interface has more than
one method? What if I wanna choose which one?

For me personally this goes into wrong direction.

Cheers,
Michał Marcin Brzuchalski

>


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

2023-04-20 Thread Michał Marcin Brzuchalski
Hi

> There is one loophole, in that an interface may require an __invoke()
> method:
>
> interface TwoInts
> {
> public function __invoke(int $a, int $b): int;
> }
>
>
I was playing around with the code and parser for this in 2020 but my idea
was to introduce a new syntax that is inspired by C# - Delegates [1]

delegate Reducer (?int $sum, int $item = 0): int;

class Foo implements Reducer {
public function __invoke(?int $sum, int $item = 0): int { }
}
function reduce(Reducer $reducer) {
var_dump($reducer(0, 5));
}
reduce(new Foo());
reduce(fn(?int $sum, int $item = 0): int => 8);

At the same time, I assumed structural typing for closures would be used.
I assumed the delegate will resolve into
interface Reducer {
public function __invoke(?int $sum, int $item = 0): int {}
}

I also noticed that once checked closure doesn't have to be checked against
the argument types and return type because it won't change which gives some
possibility to cache this type check.


> The usual discussion has involved a way to specify a callable type's
> signature, like so:
>
> function takeTwo(callable(int $a, int $b): int $c)
> {
>   return $c(1, 2);
> }
>
> But that runs quickly into the problem of verbosity, reusability, and type
> aliases, and the discussion usually dies there.
>
>
This is why initially I thought about Delegates as in C# there are not type
aliases.
The delegate essentially resolves to an interface with `__invoke(?int $sum,
int $item = 0): int` method.


> ### Structural typing for closures
>
> The third option would necessitate having similar logic in the engine to
> the first.  In this case, we take a "structural typing" approach to
> closures; that is, "if the types match at runtime, it must be OK."  This is
> probably closest to the earlier proposals for a `callable(int $x, int $y):
> int` syntax (which would by necessity have to be structural), but
> essentially uses interfaces as the type alias.
>
> function takeTwo(TwoInts $c): int
> {
> return $c(1, 2);
> }
>
> $result = takeTwo(fn(int $x, int $y): int => $x + $y);
>

I'd love to see this happening.

[1]
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Clone with

2023-04-20 Thread Michał Marcin Brzuchalski
Hi Tim,

czw., 20 kwi 2023 o 16:39 Tim Düsterhus  napisał(a):

> ...
> But please no entirely new syntax with braces as it currently is shown
> in the examples in the RFC.
>

Then we should vote for syntax. Personally, I prefer braces here
because it doesn't look like a regular function call allowing easily to
distinguish
between two different things.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Clone with

2023-04-18 Thread Michał Marcin Brzuchalski
wt., 18 kwi 2023 o 10:20 Tim Düsterhus  napisał(a):

> Hi
>
> On 4/18/23 10:10, Rowan Tommins wrote:
> > 2) How does this interact with an __clone() method? I'm guessing the
> > __clone() would be called first, and then the with-clause applied?
> >
>
> More generally the order of operations with regard to possible side
> effects and/or exceptions would be interesting.
>
> clone $something with {
>   foo() => bar(),
>   quux() => baz(),
> };
>

Just noticed the "Property name expressions" and am wondering if it could
be a separate feature
allowing for passing named arguments to functions/constructors in the same
fashion?

$something = new Something(
  foo() => bar(),
  quux() => baz(),
);

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Clone with

2023-04-17 Thread Michał Marcin Brzuchalski
Hi Máté,

pon., 17 kwi 2023 o 08:32 Máté Kocsis  napisał(a):

> Hi Everyone,
>
> Quite some time after mentioning the "clone with" construct the first time
> (at the end of the
> https://wiki.php.net/rfc/write_once_properties#run-time_behaviour
> section),
> finally I managed to create a working implementation for this feature which
> would make it possible to properly modify readonly properties
> while simplifying how we write "wither" methods:
> https://wiki.php.net/rfc/clone_with


Thanks for your efforts and for bringing that up.
I am curious if possible to implement the feature without using `with`
keyword
it visually could look pretty close to something like an object initializer
in the future:

return clone $this {c: 1};
return new Bar {c: 1};

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Brainstorming idea: inline syntax for lexical (captured) variables

2023-04-13 Thread Michał Marcin Brzuchalski
Hi Nicolas,

czw., 13 kwi 2023 o 14:40 Nicolas Grekas 
napisał(a):

> Hi Rowan, hi all!
>
> Le ven. 17 mars 2023 à 15:51, Larry Garfield  a
> écrit :
>
> > On Thu, Mar 16, 2023, at 6:05 PM, Rowan Tommins wrote:
> > > On 16/03/2023 22:14, Larry Garfield wrote:
> > >> Wouldn't the functionality described boil down to essentially just
> > materializing into a few extra lines in the constructor?  At least to my
> > ignorant non-engine brain it seems straightforward to have this:
> > >>
> > >> $a = 1;
> > >> $b = 2;
> > >> $c = 3;
> > >>
> > >> $o = new class ($a, $b) use ($c) {
> > >>public function __construct(private int $a, private int $b) {}
> > >>public function something() {}
> > >> }
> > >>
> > >> Desugar to this:
> > >>
> > >> $c = class ($a, $b) use ($c) {
> > >>private $c;
> > >>public function __construct(private int $a, private int $b) {
> > >>  $this->c = 3;  // By value only, so this should be fine?
> > >>}
> > >>public function something() {}
> > >> }
>

Have you thought about not populating property by default but instead:
* adding "use" language construct as default to all methods?
* adding ability to assign variable values from "use" to property if needed?

Like desugar to
$c = class ($a, $b) use ($c) {
private $c = $c; // optional, not required, no conflicts
public function __construct(private int $a, private int $b) use ($c) {
$this->c = $c % 2 ? 3 : 5;
}
public function something() use ($c) {
return $c;
}
}

Or there is something so wrong with this thinking I cannot see yet.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] New core autoloading mechanism with support for function autoloading

2023-04-11 Thread Michał Marcin Brzuchalski
Hi George and Dan,

pon., 10 kwi 2023 o 14:17 G. P. B.  napisał(a):

> Hello Internals,
>
> Dan and I would like to propose a new core autoloading mechanism that fixes
> some minor design issues with the current class autoloading mechanism and
> introduce a brand-new function autoloading mechanism:
> https://wiki.php.net/rfc/core-autoloading
>
> The existing SPL autoloading functions would become aliases to the new Core
> ones and will continue to work without any migrations needing to be
> performed.
>
> Hope to hear your opinions about this!
>
> Best regards,
>
> George P. Banyard
>

Thanks for bringing this up, I like the RFC and addressing function
autoload.
Can we improve the RFC with a short description of issues on SPL autoload
this RFC tries to address? It is mentioned in at least two places that this
proposal
addresses some minor issues with SPL autoload. However, I think it'd be
worth
mentioning them in RFC so the reader can get a complete picture of what
the RFC tries to address besides adding new features like function autoload.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Array spread append

2023-04-06 Thread Michał Marcin Brzuchalski
czw., 6 kwi 2023, 13:53 użytkownik Vorisek, Michael 
napisał:

> Hi Ilija,
>
> * Are integer keys preserved? I'm assuming no, as otherwise it would
> be the same as `$a + $b`.
>
> $arr[...] = $arr;
> should be the same as
> foreach ($arr as $v) { $arr[] = $v; }
>

I'd argue with that because I think the spread operator should be
consistent with preserve keys strategy used in other places.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] Array spread append

2023-04-06 Thread Michał Marcin Brzuchalski
Hi Mick

czw., 6 kwi 2023 o 10:00 mickmackusa  napisał(a):

> Call me sentimental, but are we just trying to choke out the few remaining
> reasons to keep array_push() in the language?
>
> Okay, yeah, sometimes at is a drag that the first parameter has to be
> declared in advance and is modified by reference (which means you can't
> enjoy null coalescing or short ternary syntax directly in the first
> parameter) but...
>
> The whole purpose of array_push() is to append one or more elements to an
> array.  Spreading the second parameter makes this task simple/clean.
> https://3v4l.org/RcKRD


If a parameter of array_push is a dictionary it fails with:
Fatal error: Uncaught ArgumentCountError: array_push() does not accept
unknown named parameters
See https://3v4l.org/BHPSt

Best regards,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC [Discussion]: Make unserialize() emit a warning for trailing bytes

2023-03-27 Thread Michał Marcin Brzuchalski
Hi Tim,

thanks for the RFC

pon., 27 mar 2023 o 19:04 Tim Düsterhus  napisał(a):

> Hi
>
> I'm now opening discussion for the RFC "Make unserialize() emit a
> warning for trailing bytes":
>
> 
>
> RFC: Make unserialize() emit a warning for trailing bytes
> https://wiki.php.net/rfc/unserialize_warn_on_trailing_data
>
> Proof of concept implementation is in:
>
> https://github.com/php/php-src/pull/9630
>
> 
>
> Best regards
> Tim Düsterhus
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>
 Personally, I'd like the unserialize to throw an exception if trailing
bytes are detected.
If not by default then with the use of the option passed to unserialize
function.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] First-class callable partial application

2023-03-17 Thread Michał Marcin Brzuchalski
Hi Larry,

czw., 16 mar 2023 o 23:26 Larry Garfield 
napisał(a):

> On Thu, Mar 16, 2023, at 4:14 AM, Rowan Tommins wrote:
> > On 15/03/2023 21:12, Dan Ackroyd wrote:
> >> Would it be desirable to split those two things into two separate
> >> RFCs, by having the first RFC not have native syntax support, but
> >> instead another static method on Closure? e.g. something like:
> >>
> >> Closure::partial($callable, array $position_params, array
> >> $named_params): Closure {}
> >
> >
> > Hm... now we have the first-class callable syntax, making it an instance
> > method on Closure would allow this:
> >
> > $mapFoo = array_map(...)->partial([$foo]);
> > $filterFoo = array_filter(...)->partial([1 => $foo]);
> >
> > Which could copy over the full signature, so be equivalent to this:
> >
> > $mapFoo = static fn(array ...$arrays): array => array_map($foo,
> ...$arrays);
> > $filterFoo = static fn(array $array, int $mode = 0): array =>
> > array_filter($array, $foo, $mode);
> >
> > While being a similar length to a much less rich version:
> >
> > $mapFoo = fn($array) => array_map($foo, $array);
> > $filterFoo = fn($array) => array_filter($array, $foo);
>
> Fascinating!  I... don't know if we considered something like that or not
> 3 years ago.  It's been a while.
>
> It's definitely not as nice as the integrated syntax, but it does have the
> advantage of the implementation almost certainly being rather pedestrian in
> comparison.  That approach would favor left-to-right application, but not
> force it, which is probably sufficient.
>
> As a thought experiment, if we had that syntax and functions that were
> designed to be used with them, it would look like so:
>
> function amap(callable $c, iterable $it) { ... }
> function implode(string $sep, iterable $it) { ... }
> function length(string $s) { ... }
>
> $arr = [1, 2, 3];
>
> $a2 = amap(...)->partial(chr(...))($arr);
>
> $str = implode(...)->partial(',')($a2);
>
> Or, if combined with pipes:
>
> $size = $arr
> |> amap(...)->partial(chr(...))
> |> implode(...)->partial(',')
> |> length(...);
>
> Which... is not terrible, especially as it doesn't preclude using higher
> order functions for more control.
>

Maybe we could introduce two additional methods on a Closure similar to
what Java have
https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html
* andThen() - which functionality is like a pipe operator
* apply() - which you can call without the option to bind/rebind and just
pass arguments for execution

The pipe operator can be introduced later, but we could already have the
functionality on Closure.

The above example might look readable as well:

$size = amap(...)->partial(chr(...))
->andThen(implode(...)->partial(','))
->andThen(length(...))
->apply($arr);

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC Idea - json_validate() validate schema

2023-03-01 Thread Michał Marcin Brzuchalski
Hi Deleu,

śr., 1 mar 2023 o 16:54 Deleu  napisał(a):

>
>
> On Wed, Mar 1, 2023 at 9:36 AM Michał Marcin Brzuchalski <
> michal.brzuchal...@gmail.com> wrote:
>
>>
>> Do we really need this in core? What makes it less usable as an extension?
>>
>> Cheers,
>> Michał Marcin Brzuchalski
>>
>> >
>>
>
> Extensions are not easy to install and have a complex distribution system
> that differs greatly between Windows, Debian, Ubuntu, Alpine Linux, AWS
> Lambda, etc. I wish one day we could have something as simple and
> ubiquitous as Composer installing PHP extensions, but until then the less
> amount of extensions the better for end users.
>

I agree with your last thought. The fewer extensions the better for end
users but what I have a problem with is constantly adding functions to the
standard library instead of writing a library that fulfills the need.
Along with extensions the fewer functions/classes are bundled the better
for end users.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] RFC Idea - json_validate() validate schema

2023-03-01 Thread Michał Marcin Brzuchalski
Hi Jakub

śr., 1 mar 2023, 14:09 użytkownik Jakub Zelenka  napisał:

> >
> > Question ... are you planning to incorporate this by enhancing
> > json_validate() ???
> >
>
> Yes the plan is to initially enhance json_decode and json_validate that
> would get a new $schema argument . I plan to create a class for the
> actually schema as it needs to be parsed to its own representation so it is
> convenient to have it in the object. It could be also later created from
> the different sources than just JSON string (e.g. assoc array / stdClass or
> automatic generation from the class that I mentioned before) so it will be
> better to have it in the class.
>
> Regards
>
> Jakub
>

Do we really need this in core? What makes it less usable as an extension?

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] Methods which auto-return the class instance

2022-12-23 Thread Michał Marcin Brzuchalski
Hi Daniele and Claude,

pt., 23 gru 2022 o 10:33 Claude Pache  napisał(a):

>
> > Le 23 déc. 2022 à 01:08, joke2k  a écrit :
> >
> > Hi folks,
> >
> > What do you think about having a method which returns the class instance
> > `$this` by default only IF its return type is set as `self`?
> >
> > It is very common for fluent class methods to have a verbose `return
> > $this;` ending in their body.
> > But If you have declared `self` as return type into a non-static class
> > method you have only two options to return:
> >
> > - the $this object
> > - another instance of the same class or subclass
> >
> > ... in order to avoid a return type error.
>
> It is still two options, and it is not clear in general which one to pick.
> You could also say that, if you have `object` as return type, there are two
> options to avoid a return type error: either return the `$this` object, or
> return another object.
>
> >
> > My proposal is to set the instruction `return $this;` as optional for
> > non-static class methods with `self` declared as return type.
>
>
> I’d rather have a syntax saying explicitly that you want to return $this,
> rather than letting the interpreter guess what you meant. The obvious one
> is:
>
> ```php
> public function hit(): $this { $this->counter++; }
> ```
>
> Here, there is only one possible return value, and therefore the `return`
> instruction might be reasonably omitted.
>

I like the idea of `$this` as a return type but also strongly believe that
the use of `return $this;` should be forbidden,
eventually for control flow use of `return;` might be justified.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] More Appropriate Date/Time Exceptions

2022-11-29 Thread Michał Marcin Brzuchalski
Hi Derick,

wt., 29 lis 2022, 18:41 użytkownik Derick Rethans  napisał:

> Hi,
>
> I have just published a new "More Appropriate Date/Time Exceptions" RFC
> to sort out the warnings, errors, and already existing exceptions and
> errors. There are a few minor BC breaks, of course listed in the RFC.
>
> It is published at https://wiki.php.net/rfc/datetime-exceptions
>
> Comments?
>

Sentence "This does not allow for catching Date/Time extensions as they are
not specific enough." Should be exceptions instead of extensions.

Also after backward incompatible changes section few sections are copied
twice.

In overall I like the RFC as it gives wide range of exceptions providing
detailed information. Thanks.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] [RFC][Dynamic class constant fetch]

2022-11-04 Thread Michał Marcin Brzuchalski
Hi Ilija,

pt., 4 lis 2022, 15:26 użytkownik Ilija Tovilo 
napisał:

> Hi everyone
>
> I'd like to propose a simple RFC to introduce looking up class
> constants by name. We have dedicated syntax for basically all other
> language constructs. This RFC aims to get rid of this seemingly
> arbitrary limitation.
>
> https://wiki.php.net/rfc/dynamic_class_constant_fetch


Can it be extended to non class constants and additionally deprecations
plan for constant() function?

I know it may not be the easiest but if we are about completeness and
consistency I think coins the cleanup with planned standard library
function removal would be complete.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC][Discussion] Objects can be declared falsifiable

2022-11-03 Thread Michał Marcin Brzuchalski
>
> if ($response->getStatusCode() > 199 and $response->getStatusCode() < 300)
> {
>   // do something with “true” - which has a range of 100 possibilities at
> a granular level, which we could respond to differently - possible to
> interact with $response
>
> }
> // do something with “false” - which has a range of more than 100
> possibilities at a granular level, which we could respond to differently -
> possible to interact with $response
>
> We might wrap response to create an isOk() method to move the conditional
> logic somewhere within the object itself and make the call site more
> readable.
>
> If ($response->isOk()) {
>   // do something with “true” - still able to interact with $response
>
> }
> // do something with “false” - still able to interact with $response
>

This looks way much cleaner and is easy to read and understand.
While I understand the proposed feature is opt-int it introduces more magic
that can be solved using more verbose and IMO cleaner solutions.


> With the RFC:
>
> if (new MyType($config)) {
>   // do something with “true” - can’t use MyType because not assigned
>
> }
> // reachable because possible to resolve to false - if implements
> Falsifiable and __toBool can resolve to false - can’t use MyType because
> not assigned
>
> if ($response = new MyType($config)) {
>   // do something with “true” - with the option of using $response
>
> }
> // reachable - can’t use MyType because may not be assigned
>
> $response = new MyType($config);
> If ($response) {
>   // do something with “true” - with the option of using $response
>
> }
> // do something with “false” - with the option of using $response
>

This is somehow confusing, why is the $response storing object ref is ok
while inclining the new object creation is not?
This requires more attention while reading and debugging.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC][Discussion] Objects can be declared falsifiable

2022-11-02 Thread Michał Marcin Brzuchalski
Hi Josh,

pon., 31 paź 2022 o 20:38 Josh Bruce  napisał(a):

> Hello Interntals,
>
> Someone reached out to me outside of internals regarding the RFC I
> submitted on being able to declare objects falsifiable, so, I decided to
> update and re-enter the fray.
>
> I’ve updated the references section as many of the RFCs that were under
> discussion at the time have since been implemented.
>
> I still find myself in situations where having the capability would be
> beneficial. Specifically, I’m noticing with API responses where I want to
> pass the body received from a ResponseInterface the object can check
> itself. I currently use methods such as:
>
> ->isValid()
> ->isInvalid()
> ->toBool()
>
> And similar - the isValid and isInvalid() methods are just aliases of
> toBool(), which speaks to the ability for adopters to make their interfaces
> compatible without breaking changes in their code.
>
> In the case of a conditional - looks like this:
>
> $obj = Object::init($response);
> If ($obj->isValid()) {
> // do something with $obj
> }
>
> Or:
>
> If (
> $obj = Object::init($response) and
> $obj->isValid()
> ) {
> // do something with $obj
> }
>
> Would like to be able to do something like:
>
> If ($obj = Object::init($response)) {
> // do something with $obj
> }
>
> As of today, the last example is always true. You wouldn’t be able to
> create a guard clause for the negation:
>
> If (
> $obj = Object::init($response) and
> $obj === false
> ) {
> // handle invalid object, which could include something like
> $obj->failed()
> }
>

Have you tried not initializing invalid objects? This could help you.
Also that sounds more logical to me as I don't see any reasons to
initialize invalid objects if it's a matter of simple validation instead.

P.S. I don't see it feasible to have objects that evaluate false in
logical expressions.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Compact can't resolve outer scoped variables using short closures

2022-10-19 Thread Michał Marcin Brzuchalski
śr., 19 paź 2022 o 19:18 David Rodrigues 
napisał(a):

> > I'd rather hope for `compact()` to finally be deprecated and targeted for
> removal 😛
>
> I think compact() is a good function for transferring variables from one
> point to another, but I would think about making improvements as it is
> confusing (uses the variable name, rather than the variable itself).
>
> Regarding the bug, if we use an array it should work perfectly:
>
> $x = 123;
> (fn() => [ 'x' => $x ])();
>
> https://3v4l.org/ov7TM
>
> Would it be possible to automatically convert compact() to an array at
> runtime? So I imagine that any necessary optimization can take place
> directly over the resulting array, rather than the compact itself.
>

How would you like it to work, if you pass a variable name variable to
compact then?
$x = 123;
$name = 'x';
(fn () => compact($name))();

I agree with the idea of deprecating compact() & extract() and in
long-term variable of variables as well.

Cheers,
Michał Marcin Brzuchalski


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

2022-08-26 Thread Michał Marcin Brzuchalski
Hi Tim,

pt., 26 sie 2022 o 12:15 Tim Düsterhus  napisał(a):

> Hi
>
> On 8/26/22 11:14, Hans Henrik Bergan wrote:
> >> you can't efficiently validate JSON in userland
> >
> > Has anyone actually put that claim to the test? Has anyone actually made
> a
> > userland json validator (not just wrap json_decode()/json_last_error())
> for
> > performance comparison?
> > ( if not, https://www.json.org/JSON_checker/JSON_checker.c  would
> probably
> > be a good start)
> >
>
> Worded like "you can't efficiently" the claim is false. Of course you
> can memory-efficiently validate the input by traversing the string byte
> by byte and keeping track of the nesting.
>
> However the points that make a userland implementation infeasible are:
>
> 1. Writing a JSON parser is non-trivial as evidenced by:
> https://github.com/nst/JSONTestSuite. I expect userland implementations
> to be subtly buggy in edge cases. The JSON parser in PHP 7.0+ is
> certainly more battle-tested and in fact it appears to pass all of the
> tests in the linked test suite.
>
> 2. Even if the userland implementation is written very carefully, it
> might behave differently than the native implementation used by
> json_decode() (e.g. because the latter is buggy for some reason or
> because the correct behavior is undefined). This would imply that an
> input string that was successfully validated by your userland parser
> might ultimately fail to parse when passed to json_decode(). This is
> exactly what you don't want to happen.
>

Now this is an argument I could think of.
But that one is not even mentioned in RFC.

The JSON_checker.c example delivered by json.org is probably not something
impossible
as it required around 1h of work to port it see working implementation
here https://gist.github.com/brzuchal/37e888d9b13937891c3e05fead5042bc

Cheers,
Michał Marcin Brzuchalski


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

2022-08-26 Thread Michał Marcin Brzuchalski
Hi Juan,

pt., 26 sie 2022 o 11:26 juan carlos morales 
napisał(a):

> El vie, 26 ago 2022 a las 11:00, Michał Marcin Brzuchalski
> () escribió:
> >
> > A `json_decode()` is a substitute that IMO solves 99% of use cases.
> > If I'd follow your logic and accept every small addition that handles 1%
> of use cases, somebody will raise another RFC
> > for simplexml_validate_string or yaml_validate and the next
> PhpToken::validate.
> > All above can be valid if we trust that people normally validate 300MB
> payloads to do nothing if they DON'T fail and there is nothing strange
> about that.
> >
> > Cheers,
> >
>
> How can you make such an assertion in those numbers (99% of use cases
> and son on, that you mention) ? Can you give us more information about
> this assertions?
>
> I have provide real examples where the need to validate-only a
> json-string is actually needed, also the need from our developers
> community asking for this.
>

Your examples are a couple of functions.
Assuming that they're heavily used is as true as my assumptions.

Cheers,


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

2022-08-26 Thread Michał Marcin Brzuchalski
Hi Dusk,

pt., 26 sie 2022 o 08:17 Dusk  napisał(a):

> On Aug 25, 2022, at 21:47, Michał Marcin Brzuchalski <
> michal.brzuchal...@gmail.com> wrote:
> > The same goes here and I'm not convinced we should introduce next small
> function that can be simply implemented in user land.
>
> What "simple implementation in userland" do you have in mind? Can you
> provide an example?
>
> json_decode() is not an acceptable substitute here -- as David Gebler has
> observed, decoding a large JSON structure can have a significant impact on
> memory usage, even if the data is immediately discarded. Any implementation
> based on string processing, on the other hand, is likely to be dramatically
> slower, and may have subtle differences in behavior from PHP's JSON parser.


A `json_decode()` is a substitute that IMO solves 99% of use cases.
If I'd follow your logic and accept every small addition that handles 1% of
use cases, somebody will raise another RFC
for simplexml_validate_string or yaml_validate and the next
PhpToken::validate.
All above can be valid if we trust that people normally validate 300MB
payloads to do nothing if they DON'T fail and there is nothing strange
about that.

Cheers,


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

2022-08-25 Thread Michał Marcin Brzuchalski
czw., 25 sie 2022, 21:12 użytkownik David Gebler 
napisał:

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

I share the same opinion you expressed here even though you admit in recent
email that you changed your mind.

In recent versions we tend to accept more and more small standard library
functions with IMO questionable argumentation. The same goes here and I'm
not convinced we should introduce next small function that can be simply
implemented in user land.

Any example testing > 3MB JSON string are for me edge cases that normally
don't happen often to deserve special treatment.

If we keep the tendency to pollute already bloated standard library with an
army of small functions that could have not exists and be replaced with
normal PHP counterparts IMHO we'll end with frustration from developers as
I believe DX slowly falls down here.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] Re: [Concept] Extension methods

2022-08-10 Thread Michał Marcin Brzuchalski
Hi Rowan,

śr., 10 sie 2022 o 19:32 Rowan Tommins  napisał(a):

> On Wed, 10 Aug 2022 at 17:18, Ben Ramsey  wrote:
>
> > I believe this is also called "monkey patching" in some places, and
> > Ruby, Python, and JavaScript all offer some form of object extension
> > similar to this.
> >
> > There is also the PHP runkit extension that provides some of the
> > functionality you've described: https://www.php.net/runkit7
> >
>
>
> Monkey-patching generally refers to the ability to completely "re-open" a
> class, and implement additional behaviour (or even change existing
> behaviour) *with the same privileges as the original definition*.
>
> Extension methods are a much more constrained feature - they don't break
> the class's encapsulation, only provide an extra syntax for operations that
> would already be legal. In C#, for instance, calling
> "foo.someExtensionMethod(bar)" is just syntactic sugar for the static
> method call "SomeClass.someExtensionMethod(foo, bar)", and cannot hide or
> over-ride a real method with the same name.
>
> The challenge in PHP is that so little is resolved at compile-time.
> Adapting the example from the first post:
>
> namespace App\Business;
> use extension App\CollectionExtension::map on Collection;
>
> function foo($x) {
> $x
> ->map(fn ($value) => $value + 1)
> ->map(fn ($value) => $value * 2);
> }
>

This is close to what I was thinking, there might be even more extended map
of methods and aliases similar to parentheses block known from traits use.
But what is my biggest concern is the amount of changes in opcache cuz this
proposal would require storing each Collection class entry patched by a
given extension for each class name - but these things are not really
runtime at all - meaning we may end up with a blocker because namespaces
are not a real thing in PHP.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Asymmetric visibility

2022-08-08 Thread Michał Marcin Brzuchalski
Hi Larry,

niedz., 7 sie 2022 o 21:02 Larry Garfield 
napisał(a):

> On Sun, Aug 7, 2022, at 5:54 AM, Lynn wrote:
> > On Sun, Aug 7, 2022 at 12:34 PM Rowan Tommins 
> > wrote:
> >
> >> Can you expand on where you think the ambiguity / implicitness is? As I
> >> understand it, the RFC is proposing exactly three new combined access
> >> levels:
> >>
> >> - "public private(set)"
> >> - "public protected(set)"
> >> - "protected private(set)"
> >>
> >> Although aesthetically it will take a bit of getting used to, it seems
> to
> >> me pretty clear that the first means "mostly public, but private if you
> >> want to set it", and so on.
> >>
> >> The only thing I can think of that could be described as "implicit" is
> >> that accessing a property by reference is considered a "set" operation,
> >> which I'm not sure how any implementation could avoid.
> >
> >
> > Personally for me it's the syntax. Reading "public private", "public
> > protected", or "protected private" reads really weird `public
> private(set)
> > static self $property`. In the end it makes sense if you know what it
> > means, otherwise it's probably confusing. I really like this RFC and I
> feel
> > like this might just be the way to go forward, but I have my doubts about
> > how many more keywords can be realistically added before it becomes a
> > problem.
>
> What syntax would avoid having the visibility keyword repeated?  if you
> want "public get, private set" behavior, I don't know how that could be
> done without having the words "public" and "private" both appear somewhere.
>
> Also note, since using private(set) is mutually exclusive with readonly,
> that the resulting keyword list is about the same length as the existing
> "public readonly string $foo" that has cropped up frequently with PHP 8.1.
> So... yes it's another keyword, but it's not more keywords that can exist
> simultaneously.  And moving the keyword to the right (a la C#) wouldn't
> make it any shorter; if anything it would be even more keystrokes.
>
> Very close in size, same in complexity:
>
> public readonly string $foo
> public private(set) string $foo
>

Since the radio request show already started wanted to push my 0.50€

Instead of thinking how to improve visibility on the left side, let's move
all the visibility modifiers to the right
but enclosed with parentheses, this way a future stays open for
improvements and introduction of accessors.

// instead of
class Foo {
public private(set) static int|string $id;
}

// let's do this
class Bar {
static int|string $id {
public;
private set;
};
}

A future improvement may add an accessor body on the right side of "set".

Cheers :D,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Asymmetric visibility

2022-08-05 Thread Michał Marcin Brzuchalski
Hi Larry,

pt., 5 sie 2022, 19:09 użytkownik Larry Garfield 
napisał:

> Ilija Tovilo and I are happy to present the first new RFC for PHP 8.3:
> Asymmetric Visibility.
>
> https://wiki.php.net/rfc/asymmetric-visibility
>
> Details are in the RFC, but it's largely a copy of Swift's support for the
> same.
>

Thanks for taking efforts on new RFC.

Why not C# style property accessors? It feels more natural for me while
Swift solution IMHO looks weird/odd composed with PHP class definition
syntax. The arguments in favor from the RFC look forcibly (couldn't find
better word).

Cheers,
Michał Marcin Brzuchalski


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

2022-07-29 Thread Michał Marcin Brzuchalski
Hi Juan,

pt., 29 lip 2022, 16:26 użytkownik juan carlos morales <
dev.juan.mora...@gmail.com> napisał:

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

Personally I'd vote NO.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] [RFC][Voting] Fetch properties of enums in const expressions

2022-07-06 Thread Michał Marcin Brzuchalski
Hi Ilija,

pt., 1 lip 2022 o 15:03 Ilija Tovilo  napisał(a):

> Hi everyone
>
> I opened voting for the "Fetch properties of enums in const expressions"
> RFC.
> https://wiki.php.net/rfc/fetch_property_in_const_expressions


I voted NO because the originating problem this RFC tries to solve
described in
https://github.com/php/php-src/issues/8344 is easily solvable by aither
1. introducing a simple constant string value used in both places the enum
case and as an attribute value,
2. changing the attribute argument to enum instead.

Personally, I'd see using enums as array keys feature first instead (which
the RFC reminds
in its introductory section as not possible yet) before we start improving
places around enums.

Best regards,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Exception type hint

2022-06-30 Thread Michał Marcin Brzuchalski
Hi Jeffrey,

czw., 30 cze 2022 o 17:41 Jeffrey Dafoe  napisał(a):

> > -Original Message-
> > From: Larry Garfield 
> > Sent: Wednesday, June 29, 2022 12:39 PM
> > To: php internals 
> > Subject: Re: [PHP-DEV] [RFC] Exception type hint
> >
> > On Wed, Jun 29, 2022, at 10:42 AM, Guilliam Xavier wrote:
> > > Hi (note: your message was flagged as spam),
> > >
> > >> https://github.com/php/php-src/issues/8843
> > >
> > > So I understand it as having a "true code" equivalent for the
> > > `@throws` phpDoc comment (similar to type declarations for `@param`
> > > and `@return`)? which would also be checked at run-time?
> > >
> > > Just my 2 cents on that (let's call it "exception specification"):
> > >
> > >   1. IMHO, it shouldn't be mixed in the return type declaration (with
> > > a union-like syntax) but separated and independent (e.g. with a
> > > `throws` keyword, and pipes [or commas] between multiple exception
> > > classes)
> > >   2. AFAIK, Java has it (mandatory to compile for "checked
> > > exceptions", sometimes controversial), C++ used to have it
> > > (runtime-checked) but dropped it (and introduced `noexcept` instead);
> > > I don't know of any dynamic language that has it
> > >
> > > You would also need to define how it plays with inheritance (and
> > > reflection), and what exactly should happen when a function throws an
> > > exception it didn't "declare"...
> > >
> > > PS: I also found some old feature requests:
> > >   - https://externals.io/message/4424
> > >   - https://bugs.php.net/bug.php?id=42251
> > >   - https://bugs.php.net/bug.php?id=62404
> > >   - https://bugs.php.net/bug.php?id=67312
> > >
> > > Regards,
> >
> > Side Note: Please don't top post.
> >
> > On the subject of checked exceptions, I *highly* recommend this writeup
> > from the lead of the Midori language[1].  It's long, but there's a
> section
> > specifically on exceptions (no deep link, just search the page for it)
> that goes
> > into a lot of detail about exceptions, checked exceptions, and the ways
> in
> > which both fail.  It's absolutely worth everyone's time.
> >
> > The summary for the short-timed is that the only way exceptions work,
> from
> > a reliability standpoint, is if they are 1) Rare and 2) Strictly checked
> and 3)
> > Have really good syntactic shorthand support.  And checked exceptions
> > without the other two are a recipe for hell.  Basically, it only works if
> > exceptions become an alternate syntax for an Either monad or Go's multi-
> > return.
> >
> > Since PHP is a long, long way from there, I don't believe checked
> exceptions
> > would be wise, or even slightly a good idea.  Not until/unless it's done
> as part
> > of a global rethink of error handling that reimagines how exceptions and
> > errors work at a fundamental level.  And that couldn't be done in a BC
> way
> > with the current practice of "I dunno, throw, YOLO" in PHP exceptions, so
> > they'd have to be some other, different channel.  We are definitely not
> > ready for that kind of fundamental rethink of how error handling works in
> > PHP.
> >
> > [1] http://joeduffyblog.com/2016/02/07/the-error-model/
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List To unsubscribe,
> visit:
> > https://www.php.net/unsub.php
>
> There's also a decent article here
> https://www.artima.com/articles/the-trouble-with-checked-exceptions where
> Anders Hejlsberg discusses the problems he sees with checked exceptions.
>

Thanks for the link it was really interesting to see issues with checked
exceptions based on someone's experiences.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Under Discussion] New Curl URL API

2022-06-26 Thread Michał Marcin Brzuchalski
Hi Pierrick

śr., 22 cze 2022 o 06:38 Pierrick Charron  napisał(a):

> Hi,
>
> Following our discussions we had on the subject of the new Curl URL API,
> and other curl improvements. I decided to only focus on adding the new Curl
> URL API and put aside all other improvements. Here is the RFC that reflects
> our current conversations.
>
> https://wiki.php.net/rfc/curl-url-api


TBH I have a problem with the proposed Curl* classes.
IMO they present a mix of responsibilities that I don't like.

CurlUrl is for me is a mix of Url/Uri object properties well known from
other userland implementations like the PSR one
with Uri specific like the host, scheme, port, path, query, fragment, etc.
but on the other hand, we have flags and options which
purpose is to pass Curl specific things but in IMO wrong place instead (for
instance Guzzle use separate argument in all methods for options and flags.
Secondly, it has some default logic like `setScheme` allows to put a scheme
but requires the supported one, with an exception that you can ignore
support checking by a flag - IMO this logic belongs to its consumer logic
and is not part of URL class logic and the `setPort` like above.
Next thing is that it again has all the getters and setters and is not
immutable. Why can't it be a simple constructor with read-only properties,
no getters, no setters? Maybe I miss some discussion about why here.


The same goes for CurlException which looks like is an exception for
handling some encoding of Url and not exactly to the Url properties itself.

But with all that said, if the target audience is only a user of low lever
`curl_*` functions rather than users of higher abstraction libraries like
Guzzle or Httplug then, I guess I don't care that much.
I'm only afraid that such a mix of responsibilities can lead to bad habits
when it gets to the separation of concerns by developers who get used to it
and won' see the problem as I do.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Short Closures 2, aka auto-capture take 3

2022-06-09 Thread Michał Marcin Brzuchalski
Hi Larry,

czw., 9 cze 2022 o 18:34 Larry Garfield  napisał(a):

> Last year, Nuno Maduro and I put together an RFC for combining the
> multi-line capabilities of long-closures with the auto-capture compactness
> of short-closures.  That RFC didn't fully go to completion due to concerns
> over the performance impact, which Nuno and I didn't have bandwidth to
> resolve.
>
> Arnaud Le Blanc has now picked up the flag with an improved implementation
> that includes benchmarks showing an effectively net-zero performance
> impact, aka, good news as it avoids over-capturing.
>
> The RFC has therefore been overhauled accordingly and is now ready for
> consideration.
>
> https://wiki.php.net/rfc/auto-capture-closure


Nice work. Well-described behaviors.

One question, more around future scope or related functionality in the
future:
A future RFC for "short-methods" described here in one of your declined RFC
https://wiki.php.net/rfc/short-functions in the past could be revived with
no conflicts in the scope of methods?

class Foo {
public string $firstName = 'John';
public function getFirstName(): string => $this->firstName;
}

I'm asking if I understand the scopes of this and previous RFCs correctly
and if they don't block in future "short-methods"?

Cheers,
Michał Marcin Brzuchalski


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

2022-06-07 Thread Michał Marcin Brzuchalski
Hi Dan,

pon., 6 cze 2022 o 21:15 Dan Ackroyd  napisał(a):

> Hi,
>
> I'm looking at making an RFC for subclassing PDO to expose database
> specific methods in a less magic way, aka implementing what was
> discussed here: https://externals.io/message/100773#100813
>
> I have two questions for people who use the PDO with SQLite or Postgres
>
> 1. Are any of the functions that are specific to those databases
> horribly designed and need changing? As the functions would be 'copied
> across' from where they are now, changes could be made without having
> horrible BC breaks.
>
> That is, are any of these functions horrible to use:
>
> PDO::pgsqlCopyFromArray
> PDO::pgsqlCopyFromFile
> PDO::pgsqlCopyToArray
> PDO::pgsqlCopyToFile
> PDO::pgsqlGetNotify
> PDO::pgsqlGetPid
> PDO::pgsqlLOBCreate
> PDO::pgsqlLOBOpen
> PDO::pgsqlLOBUnlink
>
> SQLIte specific functions:
> PDO::sqliteCreateAggregate
> PDO::sqliteCreateCollation
> PDO::sqliteCreateFunction
>

I admire you for picking up the gauntlet.

Personally, I'm not convinced about these methods being in PDO or in
subclasses at all.
Since PDO is a non-final class someone could already extend it and build
their own functionality around that.
If so, then how would it be solved? Auto-magically extending after let's
say PDOSqlite3 ??

I'd think of extracting driver-specific methods into a Driver / Platform
standalone type like PDODriver / PDOPlatform that is
responsible for all driver-specific methods and attributes to carry.
That one could be fetched from the PDO instance object with a new dedicated
method like "getDriver" / "getPlatform"
whatever, maybe a typed read-only property (that would be an interesting
option).

That way classes like PDOPgSQLDriver or PDOSqlite3Driver might have all the
driver methods and avoid introducing new magic related to inheritance.
There might be a transition period where these could be proxied like
currently in PDO with deprecation error, which allows for a smoother
transition.

Maybe it is just because of using Doctrine DBAL often, but IMO here a
better input might have its contributors.

Best regards,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC][Under discussion] Fetch properties in const expressions

2022-05-29 Thread Michał Marcin Brzuchalski
niedz., 29 maj 2022 o 18:24 Larry Garfield 
napisał(a):

> On Sat, May 28, 2022, at 4:44 AM, Ilija Tovilo wrote:
> > Hi everyone
> >
> > I'd like to start a discussion on a simple RFC to allow fetching
> > properties in constant expressions.
> > https://wiki.php.net/rfc/fetch_property_in_const_expressions
> >
> > The RFC proposes adding support for fetching properties in constant
> > expressions using the -> operator. I'm looking forward to your
> > feedback.
> >
> > Regards,
> > Ilija
>
> The enum-in-attribute use case came up recently in Symfony.  I'm in favor
> and the RFC looks good to me.
>

Personally, I'd start the discussion on
https://wiki.php.net/rfc/object_keys_in_arrays instead as this might solve
the need for
fetching property in constant expressions.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Discussion: String streams

2022-03-22 Thread Michał Marcin Brzuchalski
I don't have much to say on that besides that I feel it's a great idea
and if that can be built with parametrized type streams (not limited to
strings only)
then I'd be even more thrilled with such functionality.

Thanks for this idea and I hope it get materialized soon.

Cheers,
Michał Marcin Brzuchalski

pon., 21 mar 2022 o 18:10 Larry Garfield 
napisał(a):

> On Mon, Mar 21, 2022, at 10:23 AM, Sara Golemon wrote:
> > TL;DR - Yeah, PHP, but what if C++?  Feel free to tell me I'm wrong and
> > should feel bad.  THIS IS ONLY IDLE MUSINGS.
> >
> > I was reading the arbitrary string interpolation thread (which I have
> mixed
> > feelings on, but am generally okay with), and it got me thinking
> > about motivations for it and other ways we might address that.
> >
> > I spend most of my time in C++ these days and that's going to show in
> this
> > proposal, and the answer is probably "PHP isn't C++" and that's fine,
> but I
> > want you to read to the end, because XSS is perennially on my mind and
> this
> > might be one extra tool, maybe.
> >
> > PHP internal classes have the ability to handle operator overloads, and
> one
> > use for overloads I quite like from C++ is streaming interfaces.  Imagine
> > the following:
> >
> > // Don't get hung up on the name, we're a long way from bikeshedding yet.
> > $foo = (new \ostringstream) << "Your query returned " << $result->count()
> > << " rows.  The first row has ID: " >> $result->peekRow()['id'];
> >
> > At each << operator, the RHS is "shifted" into the string builder, and
> the
> > object instance is returned.  At the end $foo, is still that object, but
> > when it's echoed or cast to string it becomes the entire combined string.
> > As implementation details, we could keep the string as a list of segments
> > or materialize completely, that could also be optimized to not
> materialize
> > if we're in an output context since the intermediate complete string is
> > unnecessary.  Don't worry about this for now though.
> >
> > That by itself is... curious as an option, but not terribly interesting
> as
> > we DO have proper interpolation and it works just fine, right?
> >
> > The reason I'm bothering to introduce this is that we could also build
> > contextual awareness into this.  During instantiation we could identify
> the
> > context like:
> >
> > $forOuput = new \ostringstream\html << "You entered: " <<
> > $_POST['textarea'];
> > $forURIs = new \stringstream\uri << BASE_URI << '?''
> > foreach ($_GET as $k => $v) {
> >   $forURIs << $k '=' $v << '&';
> > }
> >
> > These specializations could perform automatic sanitization during the
> > materialization phase, this could even be customizable:
> >
> > $custom = new \ostringstream\user( landonize(...) );
> >
> > We wouldn't be giving arbitrary operator overloading to the user, only
> > arbitrary sanitization.
> >
> > Alternatively (or in addition), the point of materialization could be
> where
> > we make this decision:
> >
> > echo $stream->html();
> >
> > --
> >
> > I'd build this in userspace, but of course we don't have operator
> > overloading, so the API would be a somewhat uglier function call:
> >
> > $stream->append("This feels ")->append(FEELING::Sad);
> >
> > Maybe the right answer is open the door on user-defined operator
> overloads,
> > but my flame retardant suit is in the shop and I don't really need to
> open
> > that mixed metaphor.
> >
> > -Sara
>
> What you're proposing here is:
>
> 1. An overloadable operator on objects (via a new magic method or
> whatever) that takes one argument and returns another a new instance of the
> same class, with the argument included in it along with whatever the
> object's existing data/context is.
> 2. Using that for string manipulation.
>
> If you spell the operator >>=, then point 1 is adding a monadic bind.
> This has my full support.
>
> Using it for string manipulation is fine, although there's a bazillion
> other things we can do with it that I would also very much support and can
> be done in user space.  Whether or not it makes sense for some of these
> operations to be done in C instead is up for debate.  Once an arbitrary
> object can have a socket, that plu

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

2022-03-17 Thread Michał Marcin Brzuchalski
Hi Nocolas,

czw., 17 mar 2022 o 11:38 Nicolas Grekas 
napisał(a):

> Le jeu. 17 mars 2022 à 04:54, Saif Eddin Gmati  a
> écrit :
>
> > Hello Internals,
> >
> > As per my last email in the previous thread, i have started the vote for
> > sealed classes feature.
> >
> > The vote will run for 2 weeks until March 31st 2022.
> >
> > Discussion: https://externals.io/message/117173
> >
> > Draft Discussion: https://externals.io/message/114116
> >
> > RFC: https://wiki.php.net/rfc/sealed_classes
> >
>
> Hello Saif,
>
> Thanks for the RFC.
>
> I voted "no" because to me this closes extensibility in a hard way. If
> users are fine ignoring an "@internal" annotation, or using reflection to
> access private symbols, then I think that's fine: their problem; they know
> why they need to do so - not authors. Allowing authors to forcibly remove
> that capability from users is going too deep into removing power from
> users.
>
> Said another way, I don't think this solves any problem that authors face
> in practice. As such I don't think this is worth the added language
> complexity + removal of power.
>

I'd say this is a very weak argument, we do the same with the final on
class, method, property level already.
But well, it's your vote.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] PHP Community to support Ukraine and help to stop Russian agression

2022-03-02 Thread Michał Marcin Brzuchalski
śr., 2 mar 2022 o 14:56  napisał(a):

>
>
> Am 02-Mar-2022 13:51:07 +0100 schrieb ocram...@gmail.com:
> >
> > Hey Christian,
> >
> > On Wed, Mar 2, 2022 at 1:41 PM  wrote:
> > > this is exactly the problem. Russia did not just invaded Ukrainia out
> of nowhere. The story started in 2014 with the illegal coup d'etat against
> Viktor Yanukovych and its acceptance by the western countries. Or even
> earlier, with the eastern extension of the EU and the Nato, to get Ukriane
> on their side, stoping the political neutrality of Ukraine between Russia
> and the western.
> > >
> > > As you see, it is not as simple. Should we start a discussion now? I
> do not think so. It would not help anybody. Wars or conflicts are never
> simple. Usually there's a long story.
> > > Taking ones side in political conflicts will separate the community
> for sure.
> > >
> > > Please do not start that.
> > >
> > > You and anybody else can show their political position on twitter,
> facebook or elsewhere. We do not need to do that on php.net.
> >
> > Please GTFO: we don't need more of Putin's propaganda over here, as
> they're busy enough with butchering civilians over there.
> >
> > Greets,
> >
> > Marco Pivetta
>
> Hi Marco,
>
> this is exactly what I meant. It leads to separation of the community and
> hate against each other. You judge my statement as Putin propaganda
> although I have not said I am supporting Putin or the war. I only wanted to
> make clear, that if we start to support Ukraine as the victimized party in
> this conflict we have to do that in other conflicts, too.
>
> Look at the Iraquis who were attacked by the USA, the Uyghurs in China,
> the poulation in Noth Korea or the war in Yemen. Thousands of people are
> dying there every year and nobody is raising his voice.
>

In 7d almost 10 thousand died in Ukraine (including both sides). Not in a
year!
If you don't see this then I have no words.

--
Michał Marcin Brzuchalski


Re: [PHP-DEV] PHP Community to support Ukraine and help to stop Russian agression

2022-03-02 Thread Michał Marcin Brzuchalski
śr., 2 mar 2022 o 14:34 Aaron Junker  napisał(a):

> Hi all
>
> As I see this there is strong agreement against war, but not for taking a
> side on a conflict.
>
> So then why not showing a banner or something against war. No war or side
> in particular just for humanity and peace.
>
> I think that's something everyone could agree with.
>
> Let me know what you all think.
>

I wanted to express it by an example but cannot find better words which
took me almost 15m, so I'll try to use simple words instead.
No. IMHO that's not enough.

--
Michał Marcin Brzuchalski


Re: [PHP-DEV] PHP Community to support Ukraine and help to stop Russian agression

2022-03-02 Thread Michał Marcin Brzuchalski
śr., 2 mar 2022 o 14:00 Andreas Heigl  napisał(a):

> Hey All
>
> On 02.03.22 13:50, Marco Pivetta wrote:
> > Hey Christian,
> >
> > On Wed, Mar 2, 2022 at 1:41 PM  wrote:
> >
> >> this is exactly the problem. Russia did not just invaded Ukrainia out of
> >> nowhere. The story started in 2014 with the illegal coup d'etat against
> >> Viktor Yanukovych and its acceptance by the western countries. Or even
> >> earlier, with the eastern extension of the EU and the Nato, to get
> Ukriane
> >> on their side, stoping the political neutrality of Ukraine between
> Russia
> >> and the western.
> >>
> >> As you see, it is not as simple. Should we start a discussion now? I do
> >> not think so. It would not help anybody. Wars or conflicts are never
> >> simple. Usually there's a long story.
> >> Taking ones side in political conflicts will separate the community for
> >> sure.
> >>
> >> Please do not start that.
> >>
> >> You and anybody else can show their political position on twitter,
> >> facebook or elsewhere. We do not need to do that on php.net.
> >>
> >
> > Please GTFO: we don't need more of Putin's propaganda over here, as
> they're
> > busy enough with butchering civilians over there.
>
> Thanks Marco!
>
> Standing up against bullies is something that this community so far has
> been great at.
>
> Taking no side in a political conflict means taking the side of the
> bully. And THAT will separate the community!
>
> And taking the side of Ukraine does not make other conflicts less valid
> or cruel. It's standing up against injustice.
>

Thanks!

I do not agree to do nothing!
If this could reach anyone through Putin's propaganda, I'd say it was worth
it!
I'm pretty sure it can be explained that the support was spread because of
the clearly blatant war crimes against the Ukrainian people and totally
unjustified aggression.

--
Michał Marcin Brzuchalski


Re: [PHP-DEV] PHP Community to support Ukraine and help to stop Russian agression

2022-03-02 Thread Michał Marcin Brzuchalski
śr., 2 mar 2022 o 13:51 Marco Pivetta  napisał(a):

> Hey Christian,
>
> On Wed, Mar 2, 2022 at 1:41 PM  wrote:
>
> > this is exactly the problem. Russia did not just invaded Ukrainia out of
> > nowhere. The story started in 2014 with the illegal coup d'etat against
> > Viktor Yanukovych and its acceptance by the western countries. Or even
> > earlier, with the eastern extension of the EU and the Nato, to get
> Ukriane
> > on their side, stoping the political neutrality of Ukraine between Russia
> > and the western.
> >
> > As you see, it is not as simple. Should we start a discussion now? I do
> > not think so. It would not help anybody. Wars or conflicts are never
> > simple. Usually there's a long story.
> > Taking ones side in political conflicts will separate the community for
> > sure.
> >
> > Please do not start that.
> >
> > You and anybody else can show their political position on twitter,
> > facebook or elsewhere. We do not need to do that on php.net.
> >
>
> Please GTFO: we don't need more of Putin's propaganda over here, as they're
> busy enough with butchering civilians over there.
>

+1 full support, you got my keoboard.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [VOTE] Add array_group function

2021-12-21 Thread Michał Marcin Brzuchalski
Hello Hassan,

wt., 21 gru 2021 o 09:48 Hassan Ahmed <7sno...@gmail.com> napisał(a):

> Hello all,
>
> I would like to start a voting phase for this RFC: Add array_group function
> <https://wiki.php.net/rfc/array_column_results_grouping>
>
>
I voted "no" because I don't like populating standard library with small
functions of rare use
which are easily replaceable by a simple set of statements and/or
expressions.

Best regards,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] !instanceof operator - reaction measuremen

2021-12-13 Thread Michał Marcin Brzuchalski
pon., 13 gru 2021 o 12:10 Lynn  napisał(a):

> Heya,
>
> While I definitely agree with this, and after more than 10 years of PHP I
> still have the tendency to write `if ($object !instanceof MyClass)` anyway.
> Would it be possible, or would it collide with constants to do the
> following?
> ```
> $object === MyClass;
> $object !== MyClass;
> ```
> The reason I'm hoping this would be possible, is that I often have brainlag
> trying to write "instanceof" and I either make several typos, or I end up
> with "instance" and it takes me an error message to realize I forgot the
> "of". The "instanceof" is counterintuitive for me compared to operators.
>
> If this isn't possible and `!instanceof` would be adopted, what about the
> following in addition to the proposed example?
> ```
> $object implements MyInterface;
> $object !implements MyInterface;
> $object extends MyClass;
> $object !extends MyClass;
> ```
>

Why not "not" instead? The "!" in front of "i" in "!implements" is almost
not visible which IMO could get easily ignored unintentionally.
Instead constructs like "$foo not implements stdClass" have higher
visibility and are currently a syntax error.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Readonly Classes

2021-11-22 Thread Michał Marcin Brzuchalski
Hello Máté,

pon., 22 lis 2021 o 17:14 Máté Kocsis  napisał(a):

> Hi Internals,
>
> I'd like to propose adding support for readonly classes:
> https://wiki.php.net/rfc/readonly_classes
>
> The implementation heavily builds on the semantics of the already accepted
> readonly properties RFC (https://wiki.php.net/rfc/readonly_properties_v2),
> basically the only thing I had to implement in the PR are the following:
> - Any declared property of a readonly class is implicitly treated as
> readonly
> - Creation of dynamic properties is forbidden
>

Personally, I'm not convinced at all about this idea.
The read-only property for me is a preliminary step before introducing
full-blown property/field accessors.
Instead of making the whole class readable I'd rather see sort of data
classes similar to record classes in other languages where you get
pass-by-value, built-in object initializer and class composition over
inheritance like Go structs.
But regardless of what I'd love to see this feature, I see no justified use
case.
Therefore I ask if there are any real use cases of it? and if there are
other languages with similar functionality?

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] [Discussion] Readonly Classes

2021-11-22 Thread Michał Marcin Brzuchalski
Hi Máté,

pon., 22 lis 2021 o 17:14 Máté Kocsis  napisał(a):

> Hi Internals,
>
> I'd like to propose adding support for readonly classes:
> https://wiki.php.net/rfc/readonly_classes


Did you forget to update the status?

Cheers,
Michał


Re: [PHP-DEV] Finer control of diagnostics (deprecations, notices, and warnings)

2021-11-15 Thread Michał Marcin Brzuchalski
pon., 15 lis 2021 o 13:03 Michał Marcin Brzuchalski <
michal.brzuchal...@gmail.com> napisał(a):

> Hi Rowan,
>
> pon., 15 lis 2021 o 12:34 Rowan Tommins 
> napisał(a):
>
>> Hi all,
>>
>> Concerns have been raised a few times recently about adding new warnings
>> and deprecation notices, particularly:
>>
>> * That code bases with many instances of a particular pattern see a lot
>> of noise when a message is added
>> * That library maintainers face pressure to fix deprecations from users
>> who don't want to see those messages in their logs
>>
>> I don't think "stop adding new diagnostics to PHP" is a good solution to
>> these problems, and have thought of two ideas which might improve
>> things; both need refinement, but I hope can at least act as discussion
>> starters.
>>
>>
>> The first idea is directory-level error_reporting configuration.
>>
>> In principle, this would be very simple: a mechanism (ini setting or
>> function) that lets a user specify a different error_reporting level for
>> all code compiled from a particular directory. The most common use I
>> foresee is reducing reporting in third-party libraries, e.g.
>>
>> error_reporting=E_ALL
>> error_reporting[*/vendor/*]=E_ERROR+E_WARNING
>>
>
> IMO this screams for comments regarding
> modules/packages/assemblies however called
> where error_reporting could be controlled by vendors.
> Personally, I think that given feature users would add whole vendor
> directory,
> since the vendor/package directory is not fixed,
> may change - which in essence may go out of control and silently invoke a
> waterfall of unexpected errors.
>
>
>> This would hopefully reduce pressure on maintainers to fix deprecation
>> notices as soon as they appear, because they would no longer be
>> cluttering the user's logs.
>>
>>
>> The second idea is diagnostic codes or categories.
>>
>> This is more complicated, because it requires classifying all existing
>> diagnostics to add extra information, but would allow users to act
>> differently on specific messages. They might suppress them, downgrade
>> Warnings to Notices, or even upgrade Notices to Warnings - as they might
>> with rules in an IDE or Static Analysis tool.
>>
>> As an extension, the @ operator could be enhanced to suppress a specific
>> diagnostic, so that the following would give an "undefined variable"
>> warning, but be silent about the file not existing:
>>
>> @{FILE_NOT_FOUND}fopen($undefinedVariable, 'r');
>>
>
> This proposal allows to silence errors in certain statements but instead
> of extending silence operator
> personally, I'd prefer to enable statement-level attributes and shape them
> in an opt-in manner.
> Instead of proposing new syntax backward incompatible like this:
>
> $fp = @{FILE_NOT_FOUND}fopen($undefinedVariable, 'r');
>
> introduce statement level attributes which can be backward compatible when
> in one line
>
> $fp =
> #[SupressErrors(E_WARNING)]
> fopen($undefinedVariable, 'r');
>

My apologies this won't work for 8.0 and 8.1 since there are no
statement-level
attributes and the online attribute as a comment hack works only for <8.0
versions.

Regards,


Re: [PHP-DEV] Finer control of diagnostics (deprecations, notices, and warnings)

2021-11-15 Thread Michał Marcin Brzuchalski
Hi Rowan,

pon., 15 lis 2021 o 12:34 Rowan Tommins 
napisał(a):

> Hi all,
>
> Concerns have been raised a few times recently about adding new warnings
> and deprecation notices, particularly:
>
> * That code bases with many instances of a particular pattern see a lot
> of noise when a message is added
> * That library maintainers face pressure to fix deprecations from users
> who don't want to see those messages in their logs
>
> I don't think "stop adding new diagnostics to PHP" is a good solution to
> these problems, and have thought of two ideas which might improve
> things; both need refinement, but I hope can at least act as discussion
> starters.
>
>
> The first idea is directory-level error_reporting configuration.
>
> In principle, this would be very simple: a mechanism (ini setting or
> function) that lets a user specify a different error_reporting level for
> all code compiled from a particular directory. The most common use I
> foresee is reducing reporting in third-party libraries, e.g.
>
> error_reporting=E_ALL
> error_reporting[*/vendor/*]=E_ERROR+E_WARNING
>

IMO this screams for comments regarding
modules/packages/assemblies however called
where error_reporting could be controlled by vendors.
Personally, I think that given feature users would add whole vendor
directory,
since the vendor/package directory is not fixed,
may change - which in essence may go out of control and silently invoke a
waterfall of unexpected errors.


> This would hopefully reduce pressure on maintainers to fix deprecation
> notices as soon as they appear, because they would no longer be
> cluttering the user's logs.
>
>
> The second idea is diagnostic codes or categories.
>
> This is more complicated, because it requires classifying all existing
> diagnostics to add extra information, but would allow users to act
> differently on specific messages. They might suppress them, downgrade
> Warnings to Notices, or even upgrade Notices to Warnings - as they might
> with rules in an IDE or Static Analysis tool.
>
> As an extension, the @ operator could be enhanced to suppress a specific
> diagnostic, so that the following would give an "undefined variable"
> warning, but be silent about the file not existing:
>
> @{FILE_NOT_FOUND}fopen($undefinedVariable, 'r');
>

This proposal allows to silence errors in certain statements but instead of
extending silence operator
personally, I'd prefer to enable statement-level attributes and shape them
in an opt-in manner.
Instead of proposing new syntax backward incompatible like this:

$fp = @{FILE_NOT_FOUND}fopen($undefinedVariable, 'r');

introduce statement level attributes which can be backward compatible when
in one line

$fp =
#[SupressErrors(E_WARNING)]
fopen($undefinedVariable, 'r');

What do you think?

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] $this return type

2021-09-07 Thread Michał Marcin Brzuchalski
Hi Nikita,

wt., 7 wrz 2021 o 12:29 Nikita Popov  napisał(a):

> Hi internals,
>
> I'd like to pick up a loose thread from the future scope of the
> https://wiki.php.net/rfc/static_return_type RFC, the $this return type for
> fluent APIs:
>
> https://wiki.php.net/rfc/this_return_type
>
> I have some reservations about this (which basically come down to $this not
> being a proper "type", so should it be in the type system?) but I can see
> the practical usefulness, so I think it's worth discussing this.


If the aim of $this return type is to force and check the return $this why
would we still need/require return statement to be obligatory?
Does that make sense to assume at the end of function flow the return
$this; statement to be present by default if the return type is not an
union etc.?

Cheers,
--
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Alternative syntax for Nowdoc.

2021-06-29 Thread Michał Marcin Brzuchalski
Hi Manuel,

wt., 29 cze 2021 o 18:16 Manuel Canga  napisał(a):

> Hi, folks, here again with a new purpose:  ``` as alternative to Nowdoc
> syntax.
>
> Currently, Nowdoc syntax is very "verbose":
>
> $string =<<<'CODE'
> 
> Link: '%s'
> 
> CODE;
>
> Why doesn't something like this?:
>
> $string =```
> 
> Link: '%s'
> 
> ```;
>
> even as well:
>
> $string =```Link: '%s'```;
>
>
> I see a caveat: this is very similar to `eval` syntax. However, this
> syntax is more similar to Markdown syntax.
>
> What do you think ?
>

I think a Markdown document including PHP code snippet with above examples
could cause issues while parsing.
I can imagine parsers don't expect end-of-snippet tag "```" being not an
end tag actually.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] clamp

2021-06-24 Thread Michał Marcin Brzuchalski
czw., 24 cze 2021 o 02:15 tyson andre 
napisał(a):

> Hello Kim Hallberg,
>
> > The RFC for the clamp function is now open and under discussion, you now
> have 2 weeks
> > to discuss, suggest improvements and open issues before voting is
> considered.
>
>
> From https://wiki.php.net/rfc/clamp -
>
> > Current userland implementations are handled in several ways, some of
> which use min and max to check the bound,
> > which is costly and slow when called often.
> > Because userland implementations are for the most part not
> cost-effective when called multiple times,
> > a language implementation is desired.
>
> I'd strongly prefer an actual benchmark for context and accuracy - is it
> actually faster or slower than the most efficient userland implementation
> and by how much?
> E.g. in an optimized NTS build with `CFLAGS=-O2`, opcache
> enabled(zend_extension=opcache, opcache.enable=1,opcache.enable_cli=1),
> and no debug configure flags, how many calls per second can be made on
> variable values of $num for both?
> (I'd assume over twice as fast as calling both min/max from another
> function, but possibly slower than efficient_clamp, but haven't run this)
>
> For userland implementations that did use min/max, they probably weren't
> performance sensitive for the application.
>
> ```php
> function efficient_clamp(int|float $num, int|float $min, int|float $max):
> int|float {
> return $num < $min ? $min : ($num > $max ? $max : $num);
> }
> ```
>

Do we really need it?
IMO the performance of this is not gonna change anything much.
We're talking about nanoseconds here possibly.

I'm looking forward to Hello World RFC - that's also often implemented in
userland.

```php
function hello(?string $who = 'World', bool $return = false, bool $newline
= true): ?string {
$str = "Hello {$who}!" . ($newline ? PHP_EOL : '');
if ($return) return $str;
echo $str;
}
```

I get an impression that we constantly add things into standard library
which are from a language perspective irrelevant
and that all could be developed in userland with no harm.

Cheers,
--
Michał Marcin Brzuchalski


Re: [PHP-DEV] Consensus Gathering: is_initialized

2021-05-27 Thread Michał Marcin Brzuchalski
czw., 27 maj 2021 o 13:29 Pierre  napisał(a):

> Le 26/05/2021 à 21:24, Michał Marcin Brzuchalski a écrit :
> > I don't think nowadays anyone does that without a kind of deserializer
> > which
> > reads the metadata of desired DTO and like Symfony's Serializer or JMS
> > which just deal with such tasks!?
>
> Hello,
>
> Just for your information, we do have our own serialization mechanism in
> some projects, when writing workaround around existing serializers bugs
> or behaviors become too difficult, or when we want drastic speed-ups, or
> want to avoid dependencies. Sometime even just because the target
> production environment is not suitable for those well-known libraries
> (even in the containerized dockerized, vmized world, this still happen,
> sometime).
>
> Don't assume that everyone use X or Y library, there are some mad guys
> everywhere around the globe writing their own proprietary very complex
> APIs for pretty much anything when they have critical needs or legit
> constraints. For example we do maintain our own database access layer
> and SQL query builder, and we are pretty much anyone, just like anyone
> (why wouldn't we use Doctrine or PDO ? Yet we don't).
>

Please take no offense. I just think it's not that common.
While I do work with many integration projects most of the time already
could forget about writing my own stuff for this kind of thing where I have
learned to rely on community-developed components
which just speeds up development and just gets the things done.

I think described cases are rarely needing such function especially
if it's easy to write one using reflection.

My personal preference is to reduce the amount of standard library shipped
than add.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Consensus Gathering: is_initialized

2021-05-26 Thread Michał Marcin Brzuchalski
śr., 26 maj 2021 o 18:20 Guilliam Xavier 
napisał(a):

> On Wed, May 26, 2021 at 4:09 PM Larry Garfield 
> wrote:
>
> > On Wed, May 26, 2021, at 8:24 AM, Rowan Tommins wrote:
> > > On 26/05/2021 11:13, 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
> > >
> > >
> > > My general feeling remains that the "uninitialized" state is an awkward
> > > hack that we should be working to eliminate with better constructor
> > > semantics. A variable that remains uninitialised after the constructor
> > > almost always indicates a bug in the constructor, not a state that the
> > > rest of the application should care about.
> >
> > I am inclined to agree here.  What I don't know about is the cases noted
> > in the bug, such as GraphQL or other serialization cases where "null" and
> > "absent" are not quite the same thing.  That is probably sufficiently
> > edge-case to not deal with directly, especially when the more verbose
> > alternative still exists, but that's the only reason I'd even consider
> > making uninitialized something other than "your constructor is bad and
> you
> > should feel bad."
> >
>
> I think you said the word: serialization. And especially *deserialization*,
> e.g. from a JSON payload into a typed DTO *without* calling the constructor
> (then the DTO is passed through validation, which must handle uninitialized
> typed properties "gracefully").
>

I don't think nowadays anyone does that without a kind of deserializer
which
reads the metadata of desired DTO and like Symfony's Serializer or JMS
which just deal with such tasks!?

Not using ctor even for manual construction would be just a waste of time
writing validation etc.
Consider JSON decoded into:

$arr = ['name' => 'main_window','width' => 500,'height' => 500];
class Window {
public function __construct(
public string $title,
public string $name,
public int $width,
public int $height,
public ?bool $unknown = null,
...$additional,
) {}
}
var_dump(new Window(...$arr));

That example errors, since the title property is not given in decoded
payload.
The behaviour is what we expect here since we require it.
The solution is to pass a valid payload with the title.
Additionally, you can see "unknown" was also missing but it was initialized
with default null value since we don't require that.

If you add nullability into the title as follows:

class Window {
public function __construct(
public ?string $title = null,
public string $name,
public int $width,
public int $height,
public ?bool $unknown = null,
...$additional,
) {}
}

Then is passing built-in language sort of validation.

If you wanna allow passing more values than expected, add not used variadic
argument at the end.
Variadic argument solves the issue with missing named arguments which might
appear in the future.

These examples show a very simple solution to container classes such as DTO.
All of them avoid dealing with an uninitialized state.

IMHO there really is no need to deal with uninitialized properties in DTO!

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] Consensus Gathering: is_initialized

2021-05-26 Thread Michał Marcin Brzuchalski
śr., 26 maj 2021 o 12:14 Joe Watkins  napisał(a):

> 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.
>
> You can read both of our thoughts about it on the PR.
>
> What I'm looking for now, is reasons that we are wrong - good use cases
> that aren't born from code that is doing bad things ...
>

IMHO we don't need it, working with the typed properties since the
beginning
I thought only for a short period that I'd need this kind of feature but
shortly realized
that I'm doing it wrong if my code can reach such state,
given that all paths now lead to a known state,
object construction in all cases specifies all required properties
without having any doubts like uninitialized properties so this is doable.

If one really needs to check if a property is initialized or not I consider
it a dark magic
and such can reach up to the reflection mechanism to just check it.
IMHO it's not common (or at least should not be) to have such a need.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC]: Allow static properties in enums

2021-05-17 Thread Michał Marcin Brzuchalski
pon., 17 maj 2021, 16:31 użytkownik Larry Garfield 
napisał:

> On Mon, May 17, 2021, at 9:16 AM, Michał Marcin Brzuchalski wrote:
> > pon., 17 maj 2021, 16:02 użytkownik tyson andre <
> tysonandre...@hotmail.com>
> > napisał:
> >
> > > Hi internals,
> > >
> > > I've created a new RFC
> > > https://wiki.php.net/rfc/enum_allow_static_properties
> > >
> > > Although enums are immutable objects, it is often useful to have
> functions
> > > or methods that operate on enum instances.
> > > In many cases, it would make sense to declare that functionality as
> static
> > > methods on the enum itself.
> > > In cases where static methods require shared state, it would be useful
> to
> > > allow storing those shared state in static properties.
> > > To ensure immutability of enum instances, it's only necessary to forbid
> > > instance properties, but all properties were forbidden in the initial
> > > functionality included with the enums RFC.
> > >
> > > This RFC proposes allowing static properties in enums, while
> continuing to
> > > forbid instance properties.
> > >
> >
> > Would you be able to provide more real life example?
> > The example in RFC could easily encapsulate current Environment reading
> in
> > for eg. EnvironmentConfiguration class with static property and method
> and
> > TBH possibly that would be my preference to solve this.
>
> I would agree.  Static properties are ugly to begin with.  They're globals
> with extra syntax.  I have no desire to see them on enums.
>
> Also a clarification, since it wasn't entirely clear in Tyson's original
> email: Static methods on Enums *are already supported*.  They were included
> in the original Enum RFC.  The change proposed here is just about static
> properties.
>

Personally, I'd prefer to see enums as value objects only, adding static
properties allow to implementation of statically conditional behaviour.
IMO enums should consist only of pure functions. This is why I'd vote NO on
this proposal.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] [RFC]: Allow static properties in enums

2021-05-17 Thread Michał Marcin Brzuchalski
pon., 17 maj 2021, 16:02 użytkownik tyson andre 
napisał:

> Hi internals,
>
> I've created a new RFC
> https://wiki.php.net/rfc/enum_allow_static_properties
>
> Although enums are immutable objects, it is often useful to have functions
> or methods that operate on enum instances.
> In many cases, it would make sense to declare that functionality as static
> methods on the enum itself.
> In cases where static methods require shared state, it would be useful to
> allow storing those shared state in static properties.
> To ensure immutability of enum instances, it's only necessary to forbid
> instance properties, but all properties were forbidden in the initial
> functionality included with the enums RFC.
>
> This RFC proposes allowing static properties in enums, while continuing to
> forbid instance properties.
>

Would you be able to provide more real life example?
The example in RFC could easily encapsulate current Environment reading in
for eg. EnvironmentConfiguration class with static property and method and
TBH possibly that would be my preference to solve this.

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] [RFC] Deprecate ticks

2021-05-11 Thread Michał Marcin Brzuchalski
Hi Nikita,

wt., 11 maj 2021 o 10:53 Nikita Popov  napisał(a):

> Hi internals,
>
> I'd like to propose the depreciation of the ticks mechanism:
> https://wiki.php.net/rfc/deprecate_ticks
>
> I'm submitting this separately from the PHP 8.1 deprecations RFC, as this
> is a language change, even if not a particularly important one...
>

Glad to see this topic. That's a YES 👍

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] PHP Language Specification

2021-05-06 Thread Michał Marcin Brzuchalski
czw., 6 maj 2021, 17:23 użytkownik Sara Golemon  napisał:

> On Thu, May 6, 2021 at 10:10 AM Michał Marcin Brzuchalski <
> michal.brzuchal...@gmail.com> wrote:
>
>> czw., 6 maj 2021, 16:01 użytkownik Christoph M. Becker > >
>> napisał:
>>
>> > I wonder what to do with the PHP Language Specification[1].  Apparently,
>> > the repo is abandoned (last commit was more than a year ago, although
>> > PHP 8 changed quite some stuff).  If we don't have the bandwidth to
>> > maintain it, we should mark it as unmaintained, and maybe some of the
>> > information could be moved to the PHP manual  (I quite like the strict
>> > syntax specification, which the manual almost completely lacks).
>> >
>>
>> How much effort would it require?
>> Is there potentially someone who could help with reviews?
>>
>>
> Which part? Getting it up to date and keeping it there? Or moving the
> parts we most care about to the manual then abandoning it?
>
> I'm actually fairly happy either way, but it does need some TLC.  Some
> brave soul to step up and yes, "YES! I WILL DEFEND THE LANGUAGE
> SPECIFICATION!"  Someone with the courage to do the dirty work.  WHO WILL
> STAND AND FIGHT?!*
>

I can do this.
I love language nuances and clear explanations.
Possibly that would not be fast from my side but I believe this kind of
project doesn't have to reflect language changes immediately when it comes
to interpreter. Also a lot of time would spend on new content quality but I
believe when I ask for a help with not my native English language can
always find it.

At least I'm brave enough to pick up the gauntlet.

What do you say?

Cheers,
Michał Marcin Brzuchalski

>


Re: [PHP-DEV] PHP Language Specification

2021-05-06 Thread Michał Marcin Brzuchalski
czw., 6 maj 2021, 16:01 użytkownik Christoph M. Becker 
napisał:

> Hi all,
>
> I wonder what to do with the PHP Language Specification[1].  Apparently,
> the repo is abandoned (last commit was more than a year ago, although
> PHP 8 changed quite some stuff).  If we don't have the bandwidth to
> maintain it, we should mark it as unmaintained, and maybe some of the
> information could be moved to the PHP manual  (I quite like the strict
> syntax specification, which the manual almost completely lacks).
>
> Thoughts?
>

How much effort would it require?
Is there potentially someone who could help with reviews?

Cheers,
Michał Marcin Brzuchalski

>


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

2021-04-25 Thread Michał Marcin Brzuchalski
Hello Saif

sob., 24 kwi 2021, 13:00 użytkownik Saif Eddin Gmati 
napisał:

> A major behavior i wanted to discuss is how should sealed interfaces work,
> and specially around `Throwable` which is currently sealed to only `Error`
> and `Exception`, but allows other interfaces to extend it, and other
> classes to implement it as long as they extend `Error` or `Exception` ( or
> another class that does so ).
>
> As per the current proposal, if `Throwable` is to be declared `sealed`,
> permitting only `Error` and `Exception`, it won't be possible to extend it,
> resulting in a major BC-break, considering that too many libraries extend
> this interface in their own `ExceptionInterface`.
>
> To work around this, there's two solution:
>
> 1. don't declare `Throwable` sealed and keep it as a special case.
> 2. interfaces declared sealed, can be extended by other interfaces,
> however, classes that implement either the sealed interface directly, or
> via another interface, have to extend one of the classes the sealed
> interface permits.
>
> The second solution will allow declaring `Throwable` sealed, and would
> bring complete consistency between internally sealed symbols, and user
> land, without any BC breaks, and IMHO, it doesn't hurt as at the end, no
> one will be able to implement `Throwable` without extending the permitted
> classes.
>

I like the idea of sealed class along with proposed keywords which are
similar to already existing in other languages like Java.

Personally I'd go with the second option.

Speaking of Attributes I prefer not to use an Attribute for any particular
language feature which expects input arguments to be a valid class or
interface name for two reasons: first because there is no effective way to
restrict input string to be a valid class or interface name and second that
it'd require passing strings which means in most cases passing class or
interface name with magic ::class constant read.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] New in initializers

2021-03-03 Thread Michał Marcin Brzuchalski
Hi Nikita,

śr., 3 mar 2021, 16:04 użytkownik Nikita Popov 
napisał:

> Hi internals,
>
> I would like to propose allowing the use of "new" inside various
> initializer expressions: https://wiki.php.net/rfc/new_in_initializers
>
> In particular, this allows specifying object default values for properties
> and parameters, and allows the use of objects as attribute arguments.
>
> The RFC is narrow in scope in that it only adds support for "new". An
> extension to other call kinds should be straightforward though.
>

The reflection mechanism for properties, constants and parameters is not
described in RFC but I do believe it should for constants part. Correct me
if I'm wrong there.

The reflection for ReflectionProperty::getDefaultValue the same for
ReflectionParameter is similar and I get that it possibly should evaluate
the value on each call. But what about constants which by their nature
don't change?
Does that mean that each time ReflectionClass::getConstant is called the
value is already evaluated and the return value always refer to the same
object instance. Is that right? I guess it is.

IMO it deserves to be described in the RFC.

In general I love the proposal was especially thinking of it for static
variables.

Cheers,
Michał Marcin Brzuchalski

>


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

2021-02-26 Thread Michał Marcin Brzuchalski
Hi Manuel,

pt., 26 lut 2021 o 09:17 Manuel Canga  napisał(a):

> Hello, another example with "factories method"[1]:
>
> ```php
> use MyProject\Framework;
>
> abstract class AbstractController {
> private const HELPER_PATH = static::namespace.'/Helpers';
> private const SERVICE_PATH = static::namespace.'/Services';
>
>  public function instanceHelper( string $helperClass ) {
> $helperClassName = self::HELPER_PATH."/{$helperClass}";
>
>return new $helperClassName();
> }
>
>public function instanceService( string $serviceClass )  {
> $serviceClassName = self::SERVICE_PATH."/{$serviceClass}";
>
>return new $serviceClassName();
>}
> }
>
> use MyProject\MyModule;
>
> class Controller {
> public function __invoke() {
>  //..
>$date = $this->instanceHelper('Date');
>   //...
> }
>
> }
> ```
>
> [1]: https://en.wikipedia.org/wiki/Factory_method_pattern


Personally, none of the above examples is convincing bc I'd implement them
using a fixed class names map to avoid loading untrusted classes.
Any kind of helper class is something I'd personally not use to avoid
static coupling of code and hacks while writing unit tests over
services that could be injected by IoC.
Full class names (whether they're aliased or used in use clause) have more
benefit over class name string operations as they're easy for any renaming
which most of the IDE's these days can handle.
IMO introducing namespace magic constant has relatively narrow use and I'd
probably vote NO on this.

Cheers,
Michał Marcin Brzuchalski


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

2020-12-31 Thread Michał Marcin Brzuchalski
Hi Larry,

pon., 28 gru 2020 o 21:22 Larry Garfield 
napisał(a):

> Hello, Internalians!
>
> After considerable discussion and effort, Ilija and I are ready to offer
> you round 2 on enumerations.  This is in the spirit of the previous
> discussion, but based on that discussion a great deal has been reworked.
> The main change is that Enumeration Cases are now object instances of the
> Enumeration class rather than their own class.  Most of the other changes
> are knock-on effects of that.
>
> Of particular note:
>
> * Cases may not have methods or constants on them.  They're just dumb
> values.
> * Enums themselves may have methods, static methods, or constants.
> * Traits are supported, as long as they don't have properties.
> * The value() method on scalar enums is now a property.
>
> The full RFC is here, and I recommend reading it again in full given how
> much was updated.
>
> https://wiki.php.net/rfc/enumerations
>
> The implementation is 98% complete; there's still a few lagging bits in
> reflection, and some opcache bugs that Ilija is still stomping on.
>

I really like the shape of the current RFC.

I'd like to ask a few things:

1. Regarding the Scalar Enums since scalar values need to be literal and
by design they're read only why they use a spear "->value" on enumeration?
A spear "->" in objects is dedicated to class properties and by default
they make thinking of property which
in most cases is read-write visible.

An example using Suit enumeration from RFC:
// when I assign an enumeration to variable
$var = Suit::Spades;
// then reaching it's value using "->value"
echo $var->value; // 'C'
// Looks just like an object property fetch

By default if a property is visible it is write accessible as well, which
may confuse.

Instead of using spear "->value" would it be possible to fetch the value
just like object constants?

print Suit::Clubs::value; // 'C'
echo $var::value; // 'C'

This mentally indicates by default that it's value is constant, simple
scalar value and read only!

2. Regarding the Scalar Enums declaration syntax

enum Suit: string {
  case Hearts = 'H';
}

Would it make sense to move the part declaring enumeration value before
enum name?
I think it was put here to look similar to function return type, but IMHO
it looks better and reads easier
when moved before enum name:

enum:string Suit {
  case Hearts = 'H';
}

Leaving the space between enum name and bracket for further extensions in
future.
What do you think?


Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Enumerations

2020-12-07 Thread Michał Marcin Brzuchalski
Hi Larry,

sob., 5 gru 2020 o 00:25 Larry Garfield  napisał(a):

> Greetings, denizens of Internals!
>
> Ilija Tovilo and I have been working for the last few months on adding
> support for enumerations and algebraic data types to PHP.  This is a
> not-small task, so we've broken it up into several stages.  The first
> stage, unit enumerations, are just about ready for public review and
> discussion.
>
> The overarching plan (for context, NOT the thing to comment on right now)
> is here: https://wiki.php.net/rfc/adts
>
> The first step, for unit enumerations, is here:
>
> https://wiki.php.net/rfc/enumerations
>
> There's still a few bits we're sorting out and the implementation is
> mostly done, but not 100% complete.  Still, it's far enough along to start
> a discussion on and get broader feedback on the outstanding nits.
>
> I should note that while the design has been collaborative, credit for the
> implementation goes entirely to Ilija.  Blame for any typos in the RFC
> itself go entirely to me.
>
> *dons flame-retardant suit*
>

Thanks for taking the topic. I love it.

Regarding the `::cases()` method on UnitEnum I guess it'd be more natural
to cast enum into an array like:

(array) Suit;

but I realize it'd be harder to implement. The question is if it was even
considered?

Regarding the `::from()` method responsible for casting was a natural cast
operator considered instead?
For eg.
$suit = (Suit) $record['suit'];
Instead of:
$suit = Suit::from($record['suit']);

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Short-function syntax

2020-10-26 Thread Michał Marcin Brzuchalski
Hi David,

pon., 26 paź 2020 o 15:29 David Rodrigues 
napisał(a):

> > The use of > instead of => could if possible indicate the method being
> void
> > and reduce even more:
>
> I think that for void, it could just identify it and not return nothing
> automatically.
>
> function a(): int => b(); // equivalents to function a(): int { return
> b(); }
> function x(): void => y(); // equivalents to function x(): void { y(); }
>

Sure, but I've used > without adding return type ':void' intentionally what
could possibly indicate the void
if talking about reducing the return type at all for void methods.

Cheers,
Michał Marcin Brzuchalski


Re: [PHP-DEV] [RFC] Short-function syntax

2020-10-26 Thread Michał Marcin Brzuchalski
Hi Larry,

I'm wondering why we hadn't thought yet about reducing the need for $this
in this syntax.
Since arrow functions have an ability to capture variables defined in
parent scope why not
think of the same for class properties which will automatically reduce
short methods verbosity.

class X {
public function __construct(private int $foo, private int $bar) {}
public function getFoo(): int => $foo;
public function getBar(): int => $bar;
}

And then going further why not removing = from arrow which indicated that
there is no return value for void functions:

class X {
public function __construct(private int $foo, private int $bar) {}
public function getFoo(): int => $foo;
public function setFoo(int $value): void > $foo = $value;
public function getBar(): int => $bar;
public function setBar(int $value): void > $bar = $value;
}

The use of > instead of => could if possible indicate the method being void
and reduce even more:

class X {
public function __construct(private int $foo, private int $bar) {}
public function getFoo(): int => $foo;
public function setFoo(int $value) > $foo = $value;
public function getBar(): int => $bar;
public function setBar(int $value) > $bar = $value;
}

Would it be possible?

If not I think we should reanimate property accessors.

Just dropping my 50 cents.

Best regards,
Michał Marcin Brzuchalski

wt., 20 paź 2020 o 20:20 Larry Garfield  napisał(a):

> A while back, Nikita mentioned that it should now be easy to offer an
> abbreviated syntax for functions that are just a single expression.  I
> decided to take a crack at it and it turns out he was right.  I thus offer
> this RFC:
>
> https://wiki.php.net/rfc/short-functions
>
> Hopefully I made a decent enough case for it.  It's entirely a convenience
> factor, but I think for many OOP cases (getter methods and factored out
> operations) and functional cases (where functions should generally be a
> single expression conceptually) it does make the code nicer, more compact,
> and more readable.
>
> *dons flame retardant suit*
>
> --
>   Larry Garfield
>   la...@garfieldtech.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] RFC: execution opcode file without php source code file

2020-10-01 Thread Michał Marcin Brzuchalski
Hi,

czw., 1 paź 2020 o 11:36 肖 鑫鑫  napisał(a):

> I commit a new request path, the request is about execution opcode file
> without php source code file
> this RFC provides similar to class file of java and pyo file of python.
> patch is: https://github.com/php/php-src/pull/6146


I had exact the same feature in my mind and working implementation few
years ago
when PHP 7.0 appeared on horizon which didn't get a Zend Guard support.
I like the idea a lot.

One risk I see here is people putting whole framework or apps into one PHP
file before
calling `opcache_compile_file` to produce one big binary file.

Would it be possible to move this feature to separate function and pass
iterable list of files?
I am not sure if with current OPCache file format it's possible but if that
might reduce amount
of steps required to produce one huge OPCache file which then can be loaded
by interpreter.

Second thing worth of noting is that PR examples use CLI SAPI and lacks of
examples how
FPM can load it. Would it require at least an index.php with `

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

2020-08-16 Thread Michał Marcin Brzuchalski
Hi Benjamin,

niedz., 16 sie 2020, 11:29 użytkownik Benjamin Eberlei 
napisał:

> Following the valid criticisms of us starting the vote too early, we have
> closed the vote for this RFC for now.
>
> We look to restart the vote middle next week, so that we can close this
> before the Beta 3 release on September 3rd.
>
> We have updated the RFC at
> https://wiki.php.net/rfc/shorter_attribute_syntax_change with what we
> think
> covers all the discussion and arguments made in this and the previous
> mailing list threads.
>
> Sorry to everyone for causing this hazzle.
>
> On Mon, Aug 10, 2020 at 10:41 AM Derick Rethans  wrote:
>
> > Hi,
> >
> > I've just opened the vote to make sure we don't make a terrible mistake
> > with using the @@ syntax for attributes:
> >
> > https://wiki.php.net/rfc/shorter_attribute_syntax_change#voting
> >
> > The first vote is a vote to say that you have an opinion about attribute
> > syntax. Make sure to read up on the discussion on the mailinglist if you
> > haven't done so yet.
> >
> > The second vote is an STV vote.
> >
> > In STV you SHOULD rank *all* choices, but don't pick the same one more
> > than once, as that will invalidate your vote.
> >
> > Please have a objective look at the table
> > (https://wiki.php.net/rfc/shorter_attribute_syntax_change#proposal) and
> > don't just go by asthetics.
>

Thank you for working on this. Recent update doesn't change my vote but
made me even more confident about arguments behind #[] syntax.

The table which compares different syntaxes have an amount of minimum chars
needed for writing attribute but what I've noticed is that it differs when
considering more than 2 attributes in groupped syntax.

What I mean is that @@ requires always 2*N amount of chars which for 3
attributes is 6 while for syntaxes like #[] it is only 3 for N=1 and only
3+N-1 for N>1 which for 3 attributes is only 5 and adds always only 1
additional required chars for next additional attribute due to fact that
grouped syntax requires only one comma "," between attributes.

Cheers,
Michał Marcin Brzuchalski

>


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

2020-08-15 Thread Michał Marcin Brzuchalski
Hi Andreas,

sob., 15 sie 2020, 12:24 użytkownik Andreas Leathley 
napisał:

> On 15.08.20 11:54, Michał Marcin Brzuchalski wrote:
> > I don't think there's anything significant changed in the RFC. I really
> > doubt the vote result will change significantly.
> >
> > Currently you're the only one who wants to wipe the vote and there is no
> > much voices willing to follow your proposal.
> >
> > Personally I think extending the vote by additional week is fair enough.
>
> Next to Theodore, at least 4 other people in this mailing list have
> stated that they think the RFC process should be followed as stated in
> the RFC documents (with proper time for discussion and voting, which was
> clearly not adhered to) and/or that there is important information
> missing in the RFC, which both should lead to a change of the RFC and a
> revote.
>

If you wanna follow democratic rules then first of all 4 is not a quorum.
Secondly, you should be fine with additional voting about stopping current
RFC vote, right?

Cheers,
Michał Marcin Brzuchalski


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

2020-08-15 Thread Michał Marcin Brzuchalski
Hi Theodore,

pt., 14 sie 2020, 22:16 użytkownik Theodore Brown 
napisał:

> On Fri, Aug 14, 2020 at 2:23 PM Derick Rethans  wrote:
>
> > On Fri, 14 Aug 2020, Sara Golemon wrote:
> >
> > > > Derick and Benjamin (and Sara), are these requests reasonable? If
> > > > the RFC follows the discussion period rule and contains all the
> > > > relevant information, I will be much more confident that it is
> > > > resulting in the best long term outcome (and I think this would
> > > > speak for many others on list as well).
> > >
> > > Honestly, the current end date is fine, because the intent of the rule
> > > is met.  However, I do like that you're seeking a solution which helps
> > > to put concerns to rest.
> > >
> > > The only part which irks me is that we have 50-some votes already cast
> > > that would be thrown out and have to be redone, and that's on what is
> > > already the 3rd vote on this syntax.
> > >
> > > I'm vote fatigued, personally.  However, we're going to have to live
> > > with this syntax forever once it's out, so we should believe that we
> > > believe in it.
> >
> > As I've said, I have no problems with *extending* the time by the week
> > and a bit that I missed. I disagree about having to stop, wipe, and
> > revote. As you said, vote fatigue.
>
> Hi Derick and Sara,
>
> I don't think it's reasonable to simply extend the period, when the
> RFC has been significantly updated to include important details that
> were missing when most people cast their vote. Otherwise the vote
> result does not reflect the contents of the RFC, and therefore cannot
> be considered valid.
>
> If vote fatigue is really the most important consideration here,
> would this RFC have been brought to vote in the first place?
>

I don't think there's anything significant changed in the RFC. I really
doubt the vote result will change significantly.

Currently you're the only one who wants to wipe the vote and there is no
much voices willing to follow your proposal.

Personally I think extending the vote by additional week is fair enough.

Cheers,
Michał Marcin Brzuchalski

>


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

2020-08-13 Thread Michał Marcin Brzuchalski
Hi Theodore,

czw., 13 sie 2020 o 15:17 Theodore Brown 
napisał(a):

> On Thu, Aug 13, 2020 at 3:13 AM Michał Marcin Brzuchalski <
> michal.brzuchal...@gmail.com> wrote:
>
> > Hi Theodore,
> >
> > śr., 12 sie 2020 o 18:36 Theodore Brown 
> napisał(a):
> > > On Wed, Aug 12, 2020 at 10:25 AM Sara Golemon  wrote:
> > >
> > > > On Wed, Aug 12, 2020 at 9:48 AM Theodore Brown wrote:
> > > >
> > > > > It has just come to my attention that this RFC was rushed to vote
> > > > > after less than the minimum two week period required after it was
> > > > > brought up on list. Furthermore, discussion was still very active
> at
> > > > > that time - I certainly didn't have a chance to respond to some of
> > > > > the emails before voting began.
> > > > >
> > > > > Joe first announced this RFC on Tuesday, July 28 at 9:47 AM, and
> the
> > > > > vote was started this Monday at 3:41 AM, less than 12 days, 18
> hours
> > > > > after the announcement. Per the voting rules:
> > > >
> > > > So, 30 hours short of 2 weeks. I'm going to ascribe good intentions
> > > > in trying to get the issue resolved in the minimal timeframe. The
> > > > fact active discussion was ongoing makes this a questionable choice,
> > > > but in my opinion, purely on a matter of time, quibbling over 30
> hours
> > > > is splitting hairs. Maybe compromise on adding time to the vote end
> > > > period so that the total is greater than 4 weeks?
> > > >
> > > > > What should be done to prevent this rule from being violated?
> > > >
> > > > Vigilance. You're right to raise the concern. And let's wag a finger
> > > > over it at least. If others agree that it's premature, we can stop
> > > > the vote, but I'm not inclined to disrupt the process over such a
> > > > small variance.
> > >
> > > On top of violating the minimum two week discussion period, I believe
> > > this RFC also breaks the rule on resurrecting failed proposals. When
> > > I authored the Shorter Attribute Syntax RFC, I specifically did not
> > > include a voting option for `@:`, since this syntax was declined,
> > > and my understanding was that a six month waiting period is required
> > > before resurrecting rejected proposals. [1]
> > >
> > > But if we can vote again on `#[]` and `<<>>` after they were declined,
> > > why can't we also vote again for `@:`? This syntax has the advantage
> > > of being equally short as `@@` without any BC break.
> > >
> > > I'm really disappointed and disillusioned with how the process has
> > > been handled for this RFC. It seems like the rules are arbitrarily
> > > going out the window in order to keep voting until the desired result
> > > is reached.
> > >
> > > What is the point of having rules if they aren't followed or enforced?
> > > If anyone else is troubled by the precedent being set by this RFC,
> > > please vote No on the primary vote. I'm not sure what other recourse
> > > we have at this point.
> > >
> > > Sincerely,
> > > Theodore
> > >
> > > [1]: https://wiki.php.net/rfc/voting#resurrecting_rejected_proposals
> >
> > You hint to the fact of shorter discussion period and the fact that
> > you haven't got time to respond to all discussions while if you take
> > a closer look on ML [4] that is obvious that discussion in fact began
> > earlier and it's 3 weeks from now and to avoid insinuation you replied
> > to it [5] 3 weeks ago as well.
>
> Hi Michał,
>
> The discussion thread you're referencing did not announce an RFC. Per
> the voting rules, a "Proposal is formally initiated by creating an
> RFC on PHP wiki and announcing it on the list". After that there must
> be a minimum two week discussion period before voting starts. The
> Shorter Attribute Syntax Change RFC failed to meet this requirement.
>

True, but you cannot disagree that you knew about the discussion coming soon
and yet it was 3 weeks ago.
True that the announcement was delayed but TBH for me, discussion began
earlier
and we argue about that while more than 43 votes who voted yes in the
primary vote
had no hard feelings about it.


> > Rejected features have nothing to do with a re-vote on a syntax
> > change at least this is how I understand this. Besides you already
> > mentioned this a

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

2020-08-13 Thread Michał Marcin Brzuchalski
Hi Theodore,

śr., 12 sie 2020 o 18:36 Theodore Brown  napisał(a):

> On Wed, Aug 12, 2020 at 10:25 AM Sara Golemon  wrote:
>
> > On Wed, Aug 12, 2020 at 9:48 AM Theodore Brown wrote:
> >
> > > It has just come to my attention that this RFC was rushed to vote
> > > after less than the minimum two week period required after it was
> > > brought up on list. Furthermore, discussion was still very active at
> > > that time - I certainly didn't have a chance to respond to some of
> > > the emails before voting began.
> > >
> > > Joe first announced this RFC on Tuesday, July 28 at 9:47 AM, and the
> > > vote was started this Monday at 3:41 AM, less than 12 days, 18 hours
> > > after the announcement. Per the voting rules:
> >
> > So, 30 hours short of 2 weeks. I'm going to ascribe good intentions
> > in trying to get the issue resolved in the minimal timeframe. The
> > fact active discussion was ongoing makes this a questionable choice,
> > but in my opinion, purely on a matter of time, quibbling over 30 hours
> > is splitting hairs. Maybe compromise on adding time to the vote end
> > period so that the total is greater than 4 weeks?
> >
> > > What should be done to prevent this rule from being violated?
> >
> > Vigilance. You're right to raise the concern. And let's wag a finger
> > over it at least. If others agree that it's premature, we can stop
> > the vote, but I'm not inclined to disrupt the process over such a
> > small variance.
>
> On top of violating the minimum two week discussion period, I believe
> this RFC also breaks the rule on resurrecting failed proposals. When
> I authored the Shorter Attribute Syntax RFC, I specifically did not
> include a voting option for `@:`, since this syntax was declined,
> and my understanding was that a six month waiting period is required
> before resurrecting rejected proposals. [1]
>
> But if we can vote again on `#[]` and `<<>>` after they were declined,
> why can't we also vote again for `@:`? This syntax has the advantage
> of being equally short as `@@` without any BC break.
>
> I'm really disappointed and disillusioned with how the process has
> been handled for this RFC. It seems like the rules are arbitrarily
> going out the window in order to keep voting until the desired result
> is reached.
>
> What is the point of having rules if they aren't followed or enforced?
> If anyone else is troubled by the precedent being set by this RFC,
> please vote No on the primary vote. I'm not sure what other recourse
> we have at this point.
>
> Sincerely,
> Theodore
>
> [1]: https://wiki.php.net/rfc/voting#resurrecting_rejected_proposals


You hint to the fact of shorter discussion period and the fact
that you haven't got time to respond to all discussions while if you take a
closer look
on ML [4] that is obvious that discussion in fact began earlier and it's 3
weeks from now
and to avoid insinuation you replied to it [5] 3 weeks ago as well.

You blame others for breaking rules which in fact are not broken.
IMO you think they're broken cause of your own interpretation.
Rejected features have nothing to do with a re-vote on a syntax change
at least this is how I understand this.
Besides you already mentioned this argument on ML [1] so we can argue
actually if
a re-vote on syntax change is actually resurrecting a declined proposal
since
it was not a standalone proposal which got into a declined section of RFC's
index [2]
and yet you did it again!

You blame others for "abusing" the RFC process while you've brought to us
an RFC
with a significant ambiguity [3] which you haven't mention and it turned
out after closing a vote.
Personally I think that it was your huge failure to bring the previous @@
syntax change
RFC up to the voting without checking it's correctness.

I'm personally also disappointed with the fact that in your RFC under the
primary
vote question "Are you okay with re-voting on the attribute syntax for PHP
8.0?"
removing features like grouping ability was hidden.

Personally I think you're forcing to stop the re-vote cause of mental
connection to your previous @@ RFC and trying hard to find an argument
against the re-vote.
>From the results which are available so far, it can be seen
that your proposed syntax is no longer the leading one.
I understand it fully cause I'd be upset as well.

>From my own experience, I know that as a RFC author there has always be
a place to just let it go
cause you won't always get to convince 50+ voters to your PoV.

Cheers,
Michał Marcin Brzuchalski

[1]: https://externals.io/message/111218#111254
[2]: https://wiki.php.net/rfc#declined
[3]: https://externals.io/message/110640#110819
[4]: https://externals.io/message/01#01
[5]: https://externals.io/message/01#32


  1   2   >