Skip to content

Stringable, Comparable and Parses

Novis has a few interfaces that every program can use without use. Each one lets your objects work with a part of the language.

Stringable

An object becomes text through the interface Stringable, whose one method is toString.

A class that implements it can be written out in four places: echo, the . operator that joins two texts, a value inside a string like "{$price}", and the cast as string. Novis calls toString at each of them and uses the text it returns. An object whose class does not implement the interface is not allowed in any of the four, so no program prints something like Object#3.

Everywhere else an object stays an object. Passing one to a method that wants a string does not compile. Write as string there yourself.

Good to know: the method is called on the real class of the object, so a subclass that writes its own toString is the one that runs.

The examples below show a price with its own text form, the four places that text appears, a receipt built out of several such classes, and a class without Stringable that does not compile.

Giving a class its own text

<?nvs
// Shows a class that can be printed. `Money` stores whole cents, and `toString`
// gives the amount people read.
final class Money implements Stringable
{
public function constructor(private int $cents)
{}
public function toString(): string
{
return ($this->cents / 100) . ' EUR';
}
}
var $price = new Money(1250);
// `echo` calls `toString`. This prints 12.5 EUR.
echo $price, "\n";
// `toString` is an ordinary method, so you can also call it by name.
string $text = $price->toString();
echo $text, ' has ', Core\Str::length($text), " characters\n";
Output
12.5 EUR
12.5 EUR has 8 characters

The four places an object becomes text

<?nvs
// Shows the four places an object turns into text on its own. One `toString`
// method serves all of them.
class Tag implements Stringable
{
public function constructor(private string $word)
{}
public function toString(): string
{
return '#' . $this->word;
}
}
var $tag = new Tag('sale');
// 1. `echo` writes the text out.
echo $tag, "\n";
// 2. `.` joins the text to another string.
echo 'banner: ' . $tag, "\n";
// 3. A value inside a string is replaced by the text.
echo "banner: {$tag}\n";
// 4. `as string` gives you the text as a value you can keep.
string $kept = $tag as string;
echo $kept, "\n";
// A subclass that writes its own `toString` is the one that runs, whatever type
// the variable is declared as. This prints #SALE.
final class LoudTag extends Tag
{
public function toString(): string
{
return Core\Str::upper(parent::toString());
}
}
Tag $loud = new LoudTag('sale');
echo $loud, "\n";
Output
#sale
banner: #sale
banner: #sale
#sale
#SALE

A receipt built from value objects

<?nvs
// Shows small classes that each have a `toString` method, printed together as a
// receipt. Each line has a `Money`, and the receipt has a list of lines.
final class Money implements Stringable
{
public function constructor(private int $cents)
{}
public function plus(Money $other): Money
{
return new Money($this->cents + $other->cents);
}
public function toString(): string
{
return ($this->cents / 100) . ' EUR';
}
}
final class Line implements Stringable
{
public function constructor(public string $item, public Money $price)
{}
// The price inside the string becomes text the same way this line does.
public function toString(): string
{
return $this->item . ": {$this->price}";
}
}
array<Line> $lines = [
new Line('coffee', new Money(350)),
new Line('bread', new Money(220)),
];
var $total = new Money(0);
foreach ($lines as Line $line) {
echo $line, "\n";
$total = $total->plus($line->price);
}
echo "total: {$total}\n";
Output
coffee: 3.5 EUR
bread: 2.2 EUR
total: 5.7 EUR

An object without stringable in a string

<?nvs
// Shows that a class must implement `Stringable` before its objects can be
// written out. `Point` does not, so this program does not compile.
// proof: compile-error
class Point
{
public int $x = 1;
}
var $p = new Point();
echo "point $p\n";
Output
error[E0412]: `Point` cannot be converted to `string` here; it does not implement `Stringable`
--> 04-an-object-without-stringable-in-a-string.nvs:12:13
|
12 | echo "point $p\n";
| ^^ converted to `string` here
= help: implement `Stringable`'s `toString(): string` on the class
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

An object of a class that does not implement Stringable is the error E0412 in each of the four places. A method named toString is not enough. The class must also say implements Stringable. A class that implements Stringable and has no toString method is the error E0449.

The method name __toString is the error E0111, because a method name is written in camelCase.

An object passed to a string parameter is the error E0401. An object compared with a string using == is the error E0466.

Stringable is also a type. A parameter or a variable of type Stringable accepts an object of any class that implements it. You can use that value in the same four places.

A variable of a type such as ?Money can be null. A null value gives the empty string in each of the four places.

If toString throws an error, the echo, the . or the conversion throws that error.

Comparable

Compares two objects of your own class with <, >, <=, >= and <=>.

Those operators work on objects when the class implements Comparable. That interface has one method, compareTo, which takes another value of the same class and returns a number: negative when this value comes first, zero when neither comes first, positive when the other one does. The four ordering operators read only the sign of that number, and <=> returns the number itself. You write the order once, in one method, and all five operators follow it.

Good to know: a class that does not implement Comparable cannot be ordered. The comparison does not compile, and the message names Comparable as the fix. == does not use compareTo. Two objects of your own class are equal only when they are the same object. To check whether two values have the same contents, check that compareTo returns zero.

Comparing two values with the usual operators

<?nvs
// Shows the comparison operators working on two objects. They work because the
// class implements `Comparable` and writes the one method that interface needs.
final class FileSize implements Comparable
{
public function constructor(public uint $bytes)
{}
// Returns a negative number when this size is the smaller one. Two sizes
// that are the same give zero. A larger size gives a positive number.
public function compareTo(self $other): int
{
return $this->bytes <=> $other->bytes;
}
}
var $upload = new FileSize(2400000);
var $limit = new FileSize(1048576);
var $sameLimit = new FileSize(1048576);
// `>` reads the sign of `compareTo`. This prints `the upload is over the limit`.
if ($upload > $limit) {
echo "the upload is over the limit\n";
}
// `<=` is true when `compareTo` returns zero or a negative number, so two
// sizes that are the same pass it.
if ($limit <= $sameLimit) {
echo "the limit is within itself\n";
}
// `<=>` returns the number itself. Below zero means the value on the left
// comes first. This prints `1` and then `-1`.
echo $upload <=> $limit, "\n";
echo $limit <=> $upload, "\n";
Output
the upload is over the limit
the limit is within itself
1
-1

An order built from two properties

<?nvs
// Shows an order that reads two properties, and how a program branches on the
// number `<=>` returns.
final class Release implements Comparable
{
public function constructor(public uint $major, public uint $minor)
{}
// The major number decides first. Two releases with the same major number
// are ordered by their minor number.
public function compareTo(self $other): int
{
int $byMajor = $this->major <=> $other->major;
if ($byMajor != 0) {
return $byMajor;
}
return $this->minor <=> $other->minor;
}
}
final class Report
{
// Prints which of the two releases is the newer one.
public static function say(Release $installed, Release $available): void
{
int $order = $installed <=> $available;
if ($order < 0) {
echo "an update is available\n";
} elseif ($order > 0) {
echo "your release is newer than the one on the server\n";
} else {
echo "you are up to date\n";
}
}
}
Report::say(new Release(2, 4), new Release(3, 0));
Report::say(new Release(2, 4), new Release(2, 4));
Report::say(new Release(2, 9), new Release(2, 4));
// The operators read the same method, so the minor number orders these two.
if (new Release(2, 4) < new Release(2, 9)) {
echo "2.4 comes before 2.9\n";
}
Output
an update is available
you are up to date
your release is newer than the one on the server
2.4 comes before 2.9

Checking a request against a supported range

<?nvs
// Shows two comparisons guarding a range. A service does this to check that
// the version a client asks for is one it still answers.
final class ApiVersion implements Comparable
{
public function constructor(public uint $number)
{}
public function compareTo(self $other): int
{
return $this->number <=> $other->number;
}
}
final class Api
{
// The oldest version this service still answers.
public static function oldest(): ApiVersion
{
return new ApiVersion(3);
}
// The newest one it knows about.
public static function newest(): ApiVersion
{
return new ApiVersion(7);
}
// Returns the version to answer with, or `null` when the request asks for
// one outside the range above.
public static function accept(ApiVersion $wanted): ?ApiVersion
{
if ($wanted < Api::oldest()) {
return null;
}
if ($wanted > Api::newest()) {
return null;
}
return $wanted;
}
}
array<uint> $requested = [2, 3, 5, 7, 9];
foreach ($requested as uint $number) {
var $answer = Api::accept(new ApiVersion($number));
if ($answer == null) {
echo 'version ', $number, " is not supported\n";
} else {
echo 'version ', $answer->number, " accepted\n";
}
}
Output
version 2 is not supported
version 3 accepted
version 5 accepted
version 7 accepted
version 9 is not supported

Ordering objects without comparable

<?nvs
// Shows that `<` on two objects needs the interface `Comparable`. `Point` does
// not implement it, so this program does not compile.
// proof: compile-error
class Point
{
public int $x = 1;
}
var $a = new Point();
var $b = new Point();
if ($a < $b) {
echo "less\n";
}
Output
error[E0411]: `Point` does not implement `Comparable`; ordering two objects with `<`/`<=`/`>`/`>=`/`<=>` requires it
--> 04-ordering-objects-without-comparable.nvs:13:5
|
13 | if ($a < $b) {
| ^^^^^^^ compared here
= help: implement `Comparable`'s `compareTo(self $other): int` on the class
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

Each of the five operators on objects of a class that does not implement Comparable is the error E0411. A class that implements Comparable and has no compareTo method is the error E0449.

Both sides must have the same class. Two objects of different classes are the error E0411, even when both classes implement Comparable. This includes a subclass and its parent class. An object compared with a number is E0411 too. So is a value of a type such as ?Version, which can be null.

Each operator calls compareTo once. If compareTo throws an error, the comparison throws that error.

== does not call compareTo. For objects of your own class, $a == $b is true only when both variables are the same object. Six Core\Time classes, such as Date and Duration, are compared by their value.

Parses

Parses is the interface for a class that is built out of a piece of text.

A class that implements it writes two methods. The static method parse(tainted string $s): static returns an object of the class, or throws an error when the text is not valid. tainted says the text came from outside your program. The method format() returns the text that parse reads. Its return type is tainted string, or string when the text is always safe. Core\Router::url and Core\Uri::buildQuery call format to write the value into a link.

Novis calls parse for you when a route capture, a #[Core\Query] parameter or a command argument has the type of your class. In a route, parse runs before Core\Router\Gate::allows. In a final class, parse may return an object that already exists, such as a record from a database.

The examples below show a product code built from text, what a subclass gets back, and values from a form. Then come a class used in a route and a route that does not compile. The last one shows a final class that loads a stored order.

Building a value from text

<?nvs
// Shows a class built out of text. A product code is eight characters in upper
// case, and `parse` is the only way to make one.
final class Sku implements Parses
{
public function constructor(public tainted string $code)
{}
public static function parse(tainted string $s): static
{
// `tainted` means the text came from outside the program, such as a request.
// So every rule is checked here.
if (Core\Str::length($s) != 8) {
throw new ParseError('a product code has 8 characters');
}
if ($s != Core\Str::upper($s)) {
throw new ParseError('a product code is written in upper case');
}
return new static($s);
}
// `format` returns the text that `parse` reads.
public function format(): tainted string
{
return $this->code;
}
}
echo Sku::parse('ABC-1234')->code, "\n";
// Text the class does not accept throws a `ParseError`.
try {
echo Sku::parse('abc-1234')->code, "\n";
} catch (ParseError $e) {
echo $e->message, "\n";
}
Output
ABC-1234
a product code is written in upper case

A subclass gets its own class back

<?nvs
// Shows what the return type `static` means. `parse` is written once, and each
// subclass that inherits it gets an object of its own class.
class Code implements Parses
{
public function constructor(public tainted string $text)
{}
public static function parse(tainted string $s): static
{
if (Core\Str::length($s) == 0) {
throw new ParseError('a code is not empty');
}
// `new static` builds the class the call named, not `Code`.
return new static($s);
}
// `format` returns the text that `parse` reads.
public function format(): tainted string
{
return $this->text;
}
}
class CustomerCode extends Code
{}
class SupplierCode extends Code
{}
var $customer = CustomerCode::parse('C-77');
var $supplier = SupplierCode::parse('S-12');
// `$value is SomeClass` tests the class of an object.
if ($customer is CustomerCode) {
echo $customer->text, " is a customer code\n";
}
if ($supplier is SupplierCode) {
echo $supplier->text, " is a supplier code\n";
}
// `CustomerCode` and `SupplierCode` both extend `Code`.
// So one `array<Code>` can contain both objects.
array<Code> $codes = [$customer, $supplier];
echo Core\Arr::count($codes), " codes\n";
Output
C-77 is a customer code
S-12 is a supplier code
2 codes

Checking what a form sent

<?nvs
// Shows text from a form converted into values one by one. Each line where
// `parse` throws an error is reported to the person who sent the form.
final class Recipient implements Parses
{
public function constructor(public tainted string $address)
{}
public static function parse(tainted string $s): static
{
// `tainted` means the text came from outside the program, such as a form.
// `Core\Str::trim` returns a `tainted string` too.
tainted string $clean = Core\Str::trim($s);
if (!Core\Str::contains($clean, '@')) {
throw new ParseError('an address needs an @');
}
return new static($clean);
}
// `format` returns the text that `parse` reads.
public function format(): tainted string
{
return $this->address;
}
}
array<string> $sent = [' ada@example.com ', 'nobody', 'grace@example.com'];
array<Recipient> $accepted = [];
foreach ($sent as string $line) {
try {
$accepted[] = Recipient::parse($line);
} catch (ParseError $e) {
echo "refused \"", $line, "\": ", $e->message, "\n";
}
}
echo 'sending to ', Core\Arr::count($accepted), ' of ', Core\Arr::count($sent), "\n";
foreach ($accepted as Recipient $recipient) {
echo ' ', $recipient->address, "\n";
}
Output
refused "nobody": an address needs an @
sending to 2 of 3
ada@example.com
grace@example.com

A route capture and a query value

<?nvs
// Shows a `Parses` class used as the type of a route capture and of a query
// value. The router calls `Slug::parse` for both.
final class Slug implements Parses
{
public function constructor(public tainted string $text)
{}
public static function parse(tainted string $s): static
{
if ($s != Core\Str::lower($s)) {
throw new ParseError('a slug is written in lower case');
}
return new static($s);
}
// `format` returns the text that `parse` reads.
public function format(): tainted string
{
return $this->text;
}
}
class Posts
{
#[Core\Route(path: '/posts/{slug}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function show(Slug $slug, #[Core\Query] Slug $tag): string
{
return 'one post';
}
}
// Your code can call `parse` too. The second call throws `ParseError`.
echo Slug::parse('hello-world')->text, "\n";
try {
echo Slug::parse('Hello-World')->text, "\n";
} catch (ParseError $e) {
echo $e->message, "\n";
}
Output
hello-world
a slug is written in lower case

A route capture at a class without parses

<?nvs
// Shows that a route capture can only have a class type when the class
// implements `Parses`. `Tag` does not, so this program does not compile.
// proof: compile-error
class Tag
{
public string $text = '';
}
class Posts
{
#[Core\Route(path: '/posts/{tag}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function show(Tag $tag): string
{
return 'one post';
}
}
Output
error[E0752]: `Tag` is not a type `{tag}` can arrive at
--> 05-a-route-capture-at-a-class-without-parses.nvs:13:18
|
13 | #[Core\Route(path: '/posts/{tag}', method: Core\Http\Method::Get)]
| -------------------- the capture bound here
...
15 | public function show(Tag $tag): string
| ^^^^^^^^ no conversion from a path segment
= help: a segment is converted to the parameter's declared type, so a capture binds `string`, `int`, `uint`, `decimal`, `Date`, `TimeOfDay`, `Instant`, an enum, a set of allowed values like `'a'|'b'`, or a class implementing `Parses`. It is never a regex
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

A final class loads a stored record

<?nvs
// Shows a `final` class whose `parse` loads a stored order by its id.
// The gate checks the order before the route method runs.
use Core\Http\Method;
final class Order implements Parses
{
public function constructor(public uint $id, public string $owner)
{}
// The orders this program has stored. An unknown id gives `null`.
public static function find(uint $id): ?Order
{
return match ($id) {
1 => new Order(1, 'ann'),
2 => new Order(2, 'bob'),
default => null,
};
}
// `Order` is `final`, so `parse` may return an order that already exists.
// An id with no stored order throws `ParseError`.
public static function parse(tainted string $s): static
{
?uint $id = $s as ?uint;
?Order $order = $id == null ? null : Order::find($id);
if ($order != null) {
return $order;
}
throw new ParseError('no such order');
}
// `format` returns the id, which is the text `parse` reads.
public function format(): string
{
return "{$this->id}";
}
}
class Orders
{
// The order comes from the path, as in `/orders/1`.
#[Core\Route(path: '/orders/{order}', method: Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function show(Order $order): void
{
echo 'order ', $order->id, ' of ', $order->owner;
}
// The order comes from the query string, as in `/order?order=1`.
#[Core\Route(path: '/order', method: Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function find(#[Core\Query] Order $order): void
{
echo 'order ', $order->id, ' of ', $order->owner;
}
}
// In this example the person signed in is always `ann`.
class Gate implements Core\Router\Gate
{
// `parse` has already run, so `parameter` returns the stored order.
// This works the same for both routes.
public function allows(Core\Router\Match $route): bool
{
var $value = $route->parameter('order');
if ($value == null) {
return false;
}
Order $order = $value as Order;
return $order->owner == 'ann';
}
// A missing order gives `BadCapture` (by default `400`), and another person's order gives `Denied` (`403`).
// This method sets `404` for both, so a visitor cannot find out which ids exist.
public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void
{
if ($reason == Core\Router\Refusal::BadCapture || $reason == Core\Router\Refusal::Denied) {
Core\Response::setStatus(404);
}
echo 'not found';
}
public function failed(?Core\Router\Match $route, ?Throwable $error): void
{
echo 'Something went wrong.';
}
}
if (Core\Env::context() == Core\Env::Context::Request) {
Core\Router::dispatch(new Gate());
} else {
// Each address is tried with order 1 (ann's), order 9 (missing) and order 2 (bob's).
// This prints `200` once and then `404` twice, for each address.
var $paths = [
'/orders/1',
'/orders/9',
'/orders/2',
'/order?order=1',
'/order?order=9',
'/order?order=2',
];
foreach ($paths as string $path) {
var $response = Core\Test::request(Method::Get, $path);
echo $path, ': ', $response->status(), ' ', $response->body(), "\n";
}
}
Output
/orders/1: 200 order 1 of ann
/orders/9: 404 not found
/orders/2: 404 not found
/order?order=1: 200 order 1 of ann
/order?order=9: 404 not found
/order?order=2: 404 not found

Details

The two methods are public static function parse(tainted string $s): static and public function format(): tainted string. tainted text comes from outside your program, such as a web request or a command line.

Novis needs this interface wherever it builds an object of your class from text that came from outside. This happens for a route capture, a #[Core\Query] parameter, a command argument and a command option. If the parameter's class does not implement Parses, the program does not compile. The error says so.

In a route, parse runs before Core\Router\Gate::allows. So allows can check the object with $route->parameter('name'), and this works the same for a path capture and a query value. If parse throws, the gate's refused method gets Core\Router\Refusal::BadCapture, and the default status is 400.

The return type static means the class the call named, so a subclass that inherits parse gets an object of the subclass back. In a final class, static is that class. There, parse may return an object that already exists, such as a record it loads by its id.

parse runs for every request that matches the route, before allows. It runs whether the visitor is signed in or not. A visitor can measure how long a response takes. A lookup may take longer when the record exists, so the time can show this. To prevent that, declare the parameter as string. Then load the record in the route method, after allows has run.

Core\Router::url puts the text that format returns into its own path segment and percent-encodes it. A /, ? or # in that text cannot reach another route or start the query string.

A class that implements Parses must have two methods: parse and format. A class without one of them is the error E0449. In a class that is not final, a parse method with a return type other than static is the error E0404. A final class may write its own class name there.

parse is an ordinary static method, so your code can call it too: Slug::parse("hello"). It may throw any error. ParseError is the usual one.

format returns the text that parse reads. Core\Router::url and Core\Uri::buildQuery call it to write the value into a link. Its return type is tainted string. A class whose text is not tainted may write string.

The text that parse gets is still tainted after parse reads it. A property that stores it must have the type tainted string. A string property is the error E0401. The object that parse returns is not tainted.

A route capture or a #[Core\Query] parameter can have these types:

  • string, int, uint or decimal,
  • Core\Uuid, Date, TimeOfDay or Instant,
  • an enum, or a set of allowed values such as 'a'|'b',
  • a class that implements Parses.

A #[Core\Query] parameter can also be a bool or a DateTime. Any other class is the error E0752.

A path capture with a bad value gives one of two statuses. The router converts some types itself while it matches the path: int, uint, decimal, Core\Uuid and a set of allowed values. If the segment does not convert, this route does not match. If no other route matches, the response is 404. For a Parses class, the router matches the path first. Then it calls parse. If parse throws, the response is 400, and the method does not run.

The reference pages of Stringable, Comparable and Parses have more examples.

  • Do implement Stringable when an object has one natural way to print it.
  • Do implement Comparable when you need to sort objects or compare them with <.
  • Do check the text in parse and throw ParseError when it is wrong.
  • Do return from format the same text that parse reads. A link to a route uses that text.
  • Don’t expect == to compare the properties of two objects of your own class. Compare them yourself, or use compareTo.