Download the PHP package preflow/core without Composer

On this page you can find all versions of the php package preflow/core. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package core

Preflow Core

Foundation package for the Preflow framework. Provides the DI container, config, middleware pipeline, error handling, kernel, and application bootstrap.

Installation

Requires PHP 8.4+.

What's included

Component Description
Container PSR-11 container with autowiring and attribute injection
Config Dot-notation PHP array config
MiddlewarePipeline PSR-15 middleware stack
ErrorHandler Dev (rich HTML) / prod (the app's app/pages/_errors/, else minimal) error pages
Kernel Dual-mode (Component/Action) request dispatcher
Application Bootstrap entry point
CsrfMiddleware CSRF check on every unsafe request (origin, session or stateless token), #[CsrfExempt], expired-session handling
HTTP exceptions NotFoundHttpException, ForbiddenHttpException, UnauthorizedHttpException
NonPublicPaths Path prefixes that are not public pages (admin, member area, private files), for features that treat unknown addresses as pages
SafeReturnPath Whether a "next" / "return to" value is a safe path on this site under allowed prefixes
Version (0.75) Installed package versions from Composer: Version::installed('preflow/folio') ("0.75.0", no "v"; null when not installed), Version::label() ("0.75.0"; "dev · 01c613d" for a VCS branch or a package the root replaces; plain "dev" for a path repository, whose reference is no commit)
Route contracts Route, RouteMode, RouterInterface, ConfiguredMiddleware (route middleware with arguments)

API

Container

make() builds a new object of a class (an instance registered for it is not reused): the given parameters, by name, win over autowiring, #[Config] and #[Env]; the rest is resolved as get() would. An id bound to a class (bind(Contract::class, Impl::class)) passes them on to that class; a factory closure gets them as its second argument, and one that takes no second parameter throws a ContainerException rather than drop them (as does an instance registered under a name that is no class). Route middleware with arguments (MiddlewareWith, see preflow/routing) is built this way.

Attribute injection

#[Config('key')] reads from the registered Config instance using dot notation. #[Env('NAME')] reads from getenv(). Both support a default.

Config

ServiceProvider

Middleware

A request the app makes of itself (the SEO audit rendering a page) carries the attribute preflow.internal_render; Preflow\Core\Http\InternalRender::is($request) reads it. Middleware that records visits, counts hits or queues side effects should skip them for such a request. Since 0.54.

Every internal render (GEO's Markdown views and llms-full.txt, the SEO audit's pages, page cache rebuilds) runs in core's anonymous render scope: the request context names the rendered page, nobody is signed in, the session is hidden, the translator starts in the site's default locale with overrides off (since 0.75: an audit step run from a German admin interface rendered the pages in German on a site without a locale middleware), and the translator state and users are put back afterwards. Since 0.74 mail the page queues with Notifier::sendLater() during it is dropped (Notifier::discardingQueued()), so the request that flushes the queue afterwards sends only its own mail; send() still sends at once. Since 0.75 the request's queued cookies are set aside for the render (CookieQueue::isolated()), so a remember-me token rotated or a signed-in marker set by the request that runs an audit step still reaches its response. The audit's pages (also a step run from Folio inside an admin's request) and rebuilds also see PHP's superglobals as an anonymous visitor's (AnonymousGlobals).

Application bootstrap

boot() selects the error renderer based on app.debug, boots all providers, and wires the kernel. handle() runs the middleware pipeline and dispatches to the matched route.

Work that only some requests need. A provider can leave setup out of boot and do it on the first request that needs it:

Admin routes added later in this way go in front of a catch-all with RouteCollection::insertBefore($anchor, $entries) (preflow/routing).

JsonBodyMiddleware

Automatically decodes application/json request bodies into getParsedBody(). No manual json_decode needed in controllers.

Flash messages

FlashType enum covers the four standard severity levels. Helper functions write and read flash messages via the session.

Template helpers flash('success') and flash('error') read a single message for a given type.

Request context in page templates

Page templates rendered through the Component kernel receive a request variable with commonly needed values.

Hypermedia clients (HypermediaProtocol, 0.65)

Core never reads a client library's headers itself. Preflow\Core\Http\Hypermedia\HypermediaProtocol says what core needs to know about a client (htmx, Datastar…), and HypermediaProtocols (bound in the container, and the request attribute HypermediaProtocols::class on every request handle() passes on) holds the app's: the app's hypermedia driver first (config/app.php hypermedia, htmx by default; Preflow\Htmx\HypermediaDriver extends the interface), then those packages add for their own screens (Folio's admin ships htmx). for($request) finds the client that sent a request.

Method Used by
isFragmentRequest($request) AuthMiddleware, the expired-session answer, the page cache, GEO, request.isHtmx
isHistoryRestore($request) the page cache (a restore is served the full page, never stored), request.isFragment
fragmentTarget($request) the component endpoint (a fragment without the wrapper)
varyHeaders() the page cache key and the Vary names a stored response may use
navigate($response, ?$url) AuthMiddleware (to the login), the expired-session answer (reload), MembersView::navigate()
announceNonce($response, $nonce), nonceHeaders() SecurityHeadersMiddleware (htmx: HX-Nonce); the page cache never stores those headers, a 304 drops them
pageNonce($request) handle(): a client that sends its page's CSP nonce back is answered with it (NonceGenerator::adopt()), so the scripts and styles the response puts into the page pass the page's policy

The configured driver (hypermedia other than htmx) is built eagerly at the end of the boot, right after the service providers (also on the CLI), so its constructor may only depend on services bound by then; a driver that can't be built stops the boot.

With htmx (every built-in path) the behaviour is what it was: core adds the header-only htmx client at the start of the boot whenever preflow/htmx is installed and hypermedia is htmx, so an app without components or a template engine still treats htmx requests as such. An app on another driver gets its driver's answers everywhere; a stray HX-Request header makes no fragment for it (unless a package added htmx, as Folio does for its admin), though the default vary_headers still keep such a request's cache key apart. An app without preflow/htmx has no client: no request is a fragment for core (the default vary_headers keep the keys apart).

pageNonce() is untrusted client input: core takes it from a fragment request only (not a plain request or a history restore), a base64 value of 22+ characters, for that request only (released before after-response work), and the page cache never stores the response (refused:page-nonce). A driver reads the page's nonce client-side (script.nonce) and never prints it into the page.

config/middleware.php

Place a config/middleware.php file in your application root and return an array of middleware class names. The kernel loads it automatically — no manual $app->addMiddleware() calls needed for global middleware.

Throttle

Preflow\Core\Throttle\Throttle limits attempts (a login, a form, a code guess) in fixed windows. It is bound when config/data.php exists, stores through the DataManager in the table preflow_throttle (created by preflow migrate), and is keyed by app.key. It stores on the throttle storage alias when config/data.php defines one, otherwise on the default driver. client() throws a RuntimeException while app.key is empty or the default key: a hash salted with a public key could be brute-forced back to the IP.

Cookie queue

Preflow\Core\Http\CookieQueue holds Set-Cookie values queued during a request (the remember-me cookies of preflow/auth, whose tokens use the auth storage alias, else the default: with a JSON default and the auth tables in SQLite, set 'auth' => 'sqlite' in config/data.php). It is bound when config/auth.php exists. The middleware that queued them applies them to its response; the Kernel applies what is left to an error response, which bypasses the pipeline, so a rotated cookie is never lost. isolated(\Closure $render) (since 0.75) runs $render with the queue empty, drops what it queued and puts the earlier values back; core's internal render scope uses it.

Auth providers from config

Any class in config/auth.php providers (other than the two built-in ones) is built from the container with its config entry as config. It is built lazily (LazyUserProvider) and resolved at the end of boot(), after the service providers, so it may use services they register (e.g. Folio's type catalog). A class that is not a UserProviderInterface throws at boot.

CSRF

CsrfMiddleware checks every POST, PUT, PATCH and DELETE, with or without a session. GET, HEAD and OPTIONS are never checked. A form carries the token as the _csrf_token field (csrf_field()), JavaScript as the X-CSRF-Token header (csrf_token()). Every request that has a token (a session, or a real app.key for the stateless token) gets a Preflow\Core\Http\Csrf\CsrfToken attribute, which packages that print {{ csrf }} themselves (Folio, rbac, the form builder) read. Without a session and with an empty or the built-in default app.key there is no attribute: code reading it must handle null. The attribute is set once per request: after SessionInterface::invalidate() (a sign-in, a sign-out) it still holds the removed token, so a page rendered in that same request takes CsrfToken::generate($session) instead.

Layer 1: the origin. The first signal the browser sent decides:

  1. Sec-Fetch-Site: same-origin passes; same-site, cross-site and none are refused (unless the Origin is one of csrf.trusted_origins).
  2. else Origin: passes when it is the site's origin (app.url), the request's own scheme and host, or a trusted origin; null counts as no signal.
  3. else Referer: the same comparison on its origin.
  4. no signal at all: the token decides alone.

A refused origin is refused with any token. Behind a proxy that terminates TLS, set app.url to the public address (https://example.com): the request itself then looks like http://…, and only app.url tells the check which origin is the site's.

Layer 2: the token. Which one applies is decided by the request:

The request Check
no session; or a new session without its cookie, and no cookie at all or no session token (a public page; a browser that blocks cookies) the origin passes (no token needed: such a request comes only from the site's own pages); or, when there is no origin signal, a valid stateless token and no cookie at all (with any cookie, such as a remember-me one, it is refused)
a live session the origin does not refuse and the session's token matches; on a sign-in path a public page's valid stateless token with a passing origin also passes
a new session with its cookie (expired, or an old cookie) a stateless token with a passing origin (a public page posting into a session path); a session token is the expired case below
a new session without its cookie, but other cookies and a session token the expired case below (the browser dropped the session cookie and kept a remember-me cookie). A browser that keeps other cookies but never sends the session cookie (a Secure session cookie on a plain-http stage) gets this answer on every form but the sign-in ones

A session that held a token is always checked on that token, also when the request came without its cookie.

Stateless token. Pages without a session (sites with auth.session.paths) print a signed token: HMAC-SHA256 with app.key over a 24-hour time slot, valid in the current and the previous slot, so a page left open works for at least a day. It is not tied to the visitor (no cookie, no address), so the page stays cacheable; it is only the fallback for browsers that send no origin signal. With an empty app.key or the framework's built-in default key it is never issued nor accepted (such requests are refused), and debug mode logs a warning: set app.key.

Not checked:

To find the attribute the middleware matches the route of an unsafe request (once; the Kernel dispatches that match instead of matching again). A middleware added later that rewrites the URI of a POST therefore no longer changes which route runs: the Kernel dispatches the route the CSRF check matched.

Config (config/csrf.php, optional; a missing file means the defaults):

Paths in exempt and sign_in_paths are compared without the locale prefix (/de/login is /login); sign-in paths match exactly (a trailing slash is ignored), exempt paths as prefixes of whole segments (/hooks covers /hooks and /hooks/stripe, not /hookshot).

Failures are a 403, in one of two kinds:

Expired sessions

The session existed when the form was rendered, but not any more (it carries a session token the new session cannot match). With a refused or missing origin it is the 403 above. With a passing origin:

  1. Sign-in forms pass, with the new session and its fresh token: the posted password is the proof, and login CSRF is stopped by the origin check. Folio registers {folio path}/login, members {members path}/login and {members path}/register; a site adds its own in csrf.sign_in_paths, a package in its provider:

  2. Any other form: the site's ExpiredSessionHandler answers first (below). Without one, or when it returns null, the framework's answer: the request is not applied. A form gets a 303 back to the page it came from (the Referer when its origin is app.url or the request's own, else /) with a warning flash ("Your session had expired. Please send the form again.", in en/de/fr/it, or the site's csrf.session_expired translation) and the posted fields kept as old input, so the form shows them again (Preflow\Core\Http\OldInput, read by validation's old(), the form builder and members; never kept: _csrf_token, fields whose name contains password, uploaded files, and nothing when the kept fields exceed 64 KB). htmx gets a 204 with HX-Refresh: true, a JSON client (Accept: application/json) a 409 {"error":"session_expired"}.

Nothing runs in the visitor's name: a remember-me cookie could sign them in again, so the data waits for one more click from a page with a fresh token.

Site middleware runs inside the CSRF check, so it cannot catch these. To answer the expired case your own way (keep a draft, send the visitor to the sign-in), bind a Preflow\Core\Http\Csrf\ExpiredSessionHandler in a service provider. It gets the request (with the new session as the SessionInterface attribute and its fresh CsrfToken) and returns a response to send, or null for the framework's answer. It is called for the expired case with a passing origin only, never for a sign-in path, a mismatch on a live session, a missing token, safe methods or exempt routes.

Security rule: the request is not verified as the visitor's. Never apply posted data from an expired-session request (no save, no state change, no mail). At most keep it to prefill the form after the visitor signs in again, and let them submit it once more with a valid token. Drop _csrf_token and secrets before keeping anything.

Upgrading

Unsafe requests without a session were not checked before. A public POST endpoint called by a server (a webhook, a payment provider, a cron job over HTTP) sends no origin signal and no token, so it is now refused: mark its route #[CsrfExempt('…')], or list a file route or a path outside the router in csrf.exempt, before upgrading. Forms of the site keep working on modern browsers (the origin passes); csrf_field() now prints a token on public pages too. Set a real app.key, or browsers that send no origin headers cannot post public forms.

Browser POSTs that come from another site are refused now, also on public paths: the browser sends Sec-Fetch-Site: cross-site (a payment provider's return URL that posts back, an OAuth or SAML form_post callback). Mark such routes #[CsrfExempt('…')] too, or list their origin in csrf.trusted_origins when it is a fixed one.

Caches

The application keeps a CacheRegistry in the container. The framework registers its own caches: data.json (the JSON driver's query cache, when the JSON driver is in use) and blade (compiled Blade templates in storage/cache/blade, when the Blade engine is in use). Register yours in a provider so tooling can list and clear them:

If you bind your own Twig engine or router with a cache path, register that same path like this (DirectoryCache('twig', …) for compiled templates, FileCache('routes', …) for a route table). Core's own Twig engine compiles into storage/cache/twig/{key}, where the key follows composer's installed.json, so an install or update never serves templates compiled by the previous packages; cache:clear empties every key. A DirectoryCache folder must be an absolute path other than /; anything else throws an InvalidArgumentException. Subfolders that can't be read are skipped.

Keys must be unique; a duplicate throws a LogicException. Implement CacheSource for anything else (key(), label(), stats(), clear()). OpcacheStatus reports and resets PHP's OPcache for the current SAPI.

Page cache (config/page_cache.php)

The page cache keeps finished pages for visitors who are not signed in, under storage/cache/pages/{release key}, and is listed and cleared as the pages cache (preflow cache:clear pages, Folio's Cache screen). It is off until a site switches it on:

Boot manifest (preflow optimize)

preflow optimize (preflow/devtools) writes bootstrap/cache/boot.php: what boot otherwise reads and scans on every request although it only changes on deploy. It holds:

A boot uses it only when all of these hold; otherwise it boots live, exactly as without one:

Environment variables set only by the web server (SetEnv, the FPM pool, the hosting panel) and not named in .env are not watched: after changing one, run preflow optimize again. optimize --check runs in the CLI and compares the CLI's environment, so it can't see a variable that the web server sets to a different value than the shell: --check says "current" while every web request boots live (correct, only slower). To confirm a site really uses its manifest, check from a web request (timing, or a temporary debug header), not only with --check.

Secrets. A config file that reads a secret (getenv('DB_PASS'), app.key) puts its value in the manifest, so a secret that only the web server or the deploy shell sets now also lands on disk. The file gets the .env's permission bits (0640 without a .env), lives under the release in bootstrap/cache/, outside public/; keep it there and don't commit it (see below).

OPcache with opcache.validate_timestamps=0. Running optimize again in place (same release path) doesn't reach the web server's OPcache, which keeps serving the old compiled manifest until it is reset: reset OPcache afterwards (Folio → Settings → Cache → Reset OPcache, or your deploy's reset). A deploy to a new release path is not affected.

Toggling an extension (Folio's Settings → Extensions, folio:extensions:*) rewrites extensions.json and removes the manifest: the change applies on the next request, and the site boots live until the next deploy or preflow optimize. Stored settings are never in it. Everything else in it (config files, code, model files, installed.json) is trusted until the next preflow optimize: run it on every deploy, after composer install and migrations / folio:extensions:apply, before the release goes live. preflow optimize --check lists the sources that changed since (exit 1), each once, and preflow cache:clear removes the manifest (cache boot), as does "Clear all" on Folio's Cache screen: the site stays correct and boots live until the next deploy or preflow optimize. A failed optimize (the build or the write) removes it too, so the manifest of the code before is never left in place. The file holds config values, secrets included: it gets the .env's file permissions, is per release and must not be committed. Add this to the site's .gitignore:

A package keeps its own deploy-time data in the manifest with $app->bootManifest()->remember('vendor.key', fn () => …, [$sourcePath]): the closure runs live without a manifest and while one is built; with a manifest its stored value comes back. The value must be exportable (scalars, arrays, enums) and depend only on code, config files and files that change on deploy, never on stored data or the request. $manifest->whenBuilding(fn (Application $app) => …) resolves a lazy service while the manifest is built, so its catalog is in it. A package's routes go in as a set of their own: $router->getCollection()->addMany($router->compiled('vendor.name', fn () => [...entries])) ($router is the Preflow\Routing\Router bound as RouterInterface); the same rules apply. A page or controller added on the server without a deploy is not routed until the next preflow optimize (optimize --check lists app/pages as changed).

HTTP exceptions

Throw these anywhere in the request lifecycle — ErrorHandler converts them to the correct status code automatically.

Your own error pages

A live site answers errors with a plain built-in page. Put templates in app/pages/_errors/ to answer with your own pages instead, rendered through the app's engine like any file page, so they extend your layout (since 0.66):

Non-public paths

Preflow\Core\Http\NonPublicPaths is a list of path prefixes that are not public pages. The application keeps one in the container, holding /--component from the start; packages add theirs in their provider (Folio its admin prefix, members its path, media its private_url):

A prefix matches whole segments: /folio covers /folio and /folio/x, not /folios. '' and / are ignored (they would cover the whole site). matches($path) and all() read the list. Redirects and the not-found list (preflow/routing) never answer or record a 404 under these paths. Add the prefix of any area of your own that is not a page (an API, a webhook endpoint).

Safe return paths

Preflow\Core\Http\SafeReturnPath::check($next, $allowedPrefixes) (since 0.72) judges a "next" or "return to" value from the request before a redirect goes there. It returns $next unchanged when it is a path on this site under one of the prefixes, else null:

Members' SafeNext builds on it with the member pages and next.allow, in every locale.

Pages from controllers

A file page (app/pages/*.twig) answers GET with status 200. Use a controller page when you need a 404 with your layout, a POST that shows a page, or a choice of template at run time. Inject Preflow\View\PageResponder and call render($template, $context, $status, $headers): the template gets the same request and route variables as a file page (your context keys win), collected CSS/JS is injected, and the answer is text/html; charset=UTF-8.

route is empty in a controller page; pass 'route' => (object) [...] if the template needs it. Anonymous GET pages from controllers go through the page cache like file pages do.

JSON APIs (config/api.php)

A controller action that returns an array or a JsonSerializable answers JSON; no response object needed. Preflow\Core\Http\Json builds the rest: Json::response($body, $status, $headers), Json::data($data, $meta) (the {"data": …, "meta": …} envelope; meta only when given), Json::noContent() (204) and Json::FLAGS (the encoding flags: unescaped slashes and unicode, zero fractions kept, exceptions on failure). Every JSON response, errors included, is Content-Type: application/json.

config/api.php (all keys optional; without the file the defaults apply and CORS is off):

Get a token with preflow auth:token <email-or-id> (preflow/devtools, see preflow/auth's README).

Request bodies. A malformed JSON body answers 400 on every path, instead of arriving as an empty body.

Errors. For a path under an API prefix, or a request whose Accept asks for JSON without text/html, an error answers {"message": "<text>"} instead of the HTML error page. A 422 adds "errors": {"<field>": ["<message>", …]}; in debug mode "debug": {"exception", "message", "file", "line"} is added. An HttpException's own message is shown (it is written for the client); any other exception shows Server Error, never its message outside debug. An HttpException can carry $headers (Allow, WWW-Authenticate), which go on the response.

CORS. With cors.origins set, CorsMiddleware runs outermost: it answers preflight (OPTIONS with Access-Control-Request-Method) for API paths without reaching the router, and adds its headers to every API response, error responses included. Every API response also gets Vary: Origin, so a shared cache keeps the origins apart.

The page cache never stores API paths (they are non-public paths, and every api.prefixes entry is registered as one). Caching API GETs is on the roadmap; it needs its own design, because bearer requests must never get or store a shared copy.

Upgrading to 0.62. A site without config/api.php changes in five visible ways:

  1. A wrong method on an existing path (not a catch-all) answers 405 with Allow instead of 404.
  2. An uncaught ValidationException answers 422 instead of 500 (HTML pages too).
  3. A malformed JSON request body answers 400; it used to be ignored.
  4. A request with Accept: application/json (without text/html) gets a JSON error body instead of the HTML error page. A 404 that a site middleware catches (NotFoundHttpException, a branded not-found page) stays the site's HTML.
  5. /api is the default API prefix: paths under it are non-public (page cache, redirects, not-found list, SEO and GEO skip them) and answer errors as JSON; set 'prefixes' => [] in config/api.php to opt out.

A site middleware that catches NotFoundHttpException does not see 405s: they render the framework's error page. HTML error pages, CSRF and sessions behave as before for everything else, and so does the page cache outside /api.


All versions of core with dependencies

PHP Build Version
Package Version
Requires php Version >=8.4
psr/container Version ^2.0
psr/http-message Version ^2.0
psr/http-server-handler Version ^1.0
psr/http-server-middleware Version ^1.0
psr/http-factory Version ^1.0
nyholm/psr7 Version ^1.8
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package preflow/core contains the following files

Loading the files please wait ...