Support

Sometimes its just nice to have a package which can contain some handy little tools for those special cases that often show up in an application's lifecycle.

Installation

Publish the config files for features (config/features.php) and Stringy (config/stringy.php):

php artisan vendor:publish --provider="Grafite\Support\SupportProvider"

Helpers

Helpers are handy tools for regular things we have to do in our applications such as String manipulation or extraction.

RouteHelper

route_link_class($route, $active = 'active', $class = 'nav-link')

This global method will let you handle auto setting a link as active.

Session Helper

session_error_message()

This will implode all errors from the responses with error messages.

javascript_session_data($nonce = false)

This helper method lets use initialize an app with a simple notion of window.app with window.app.session which we can use for various error and success message notification tools, including Laravel Echo etc.

In order to have this above method work correctly you need to add this trait to your User Model: HasJavascriptData

Version Helper

app_version()

Returns the current application version. It reads the latest version from your CHANGELOG.md and appends a build hash derived from your compiled public/build/assets, which is handy for cache-busting.

Stringy

Stringy is a helper for handling extraction of key information from strings. To begin using Stringy we simply call it as Stringy::of($string).

Methods

keywords() // get the keywords of a string
phrases() // get the phrases of a string
wordCount() // get the word count of a string
readTime() // estimated read time in minutes (200 words per minute)
characterCount() // get the character count of a string
keySentence() // get the key sentence from a string
summary() // create a summary of the string
calculate() // perform a math calculation of a string ex. 2 * 4 / 2
hashtags() // get the hashtags in a string
urls() // get the urls from a string
mentions() // get the mentions from a string
ipAddresses() // get the IP addresses in a string
emailDomains() // get the domains of any email addresses in a string
insert(array $data) // insert key values from your data into your string `:age` is swapped for `['age' => 47]`
mask($pattern) // convert a string to match the pattern
asPostalCode() // convert string to proper postal code format
asPhone() // convert the string to phone number format
asPlainText() // output the string as plain text

Text Analysis

Stringy can break a string down into its parts. HTML is stripped before analysis, and each of these returns a collection except syllableCount().

words() // collection of lowercased word tokens
sentences() // split into sentences, aware of abbreviations and decimals
paragraphs() // split into paragraphs
uniqueWords() // each word once
withoutStopwords() // words with common stopwords removed
nGrams($size = 2, $withoutStopwords = false) // word sequences of the given size
wordFrequency($withoutStopwords = false) // word => count, most frequent first
syllableCount() // total syllables in the string

Readability

Score how hard a piece of text is to read. Empty or unpunctuated input returns 0.0 rather than dividing by zero.

readingEase() // Flesch Reading Ease, higher is easier
gradeLevel() // mean of the grade based formulas
lexicalDensity() // share of words carrying meaning
typeTokenRatio() // vocabulary richness
readability() // every metric at once

readability() returns a collection covering Flesch Reading Ease, Flesch-Kincaid, Gunning Fog, SMOG, Coleman-Liau and ARI, plus the underlying counts:

Stringy::of('Support is a collection of handy tools for Laravel apps. It can break a string down into words and sentences. It can also score how hard the text is to read.')->readability();

[
    'fleschReadingEase' => 87.19,
    'fleschKincaidGrade' => 3.67,
    'gunningFog' => 6.71,
    'smog' => 7.79,
    'colemanLiau' => 4.86,
    'automatedReadabilityIndex' => 2.58,
    'gradeLevel' => 5.12,
    'interpretation' => 'Easy',
    'words' => 31,
    'sentences' => 3,
    'syllables' => 40,
    'complexWords' => 2,
    'averageSentenceLength' => 10.33,
    'averageSyllablesPerWord' => 1.29,
    'lexicalDensity' => 0.4516,
    'typeTokenRatio' => 0.871,
]

The interpretation is a plain language reading of the Flesch Reading Ease score:

  • 90 and above: Very Easy
  • 80 - 89: Easy
  • 70 - 79: Fairly Easy
  • 60 - 69: Standard
  • 50 - 59: Fairly Difficult
  • 30 - 49: Difficult
  • Below 30: Very Confusing

Sentiment

Sentiment scoring follows the VADER model, so it accounts for negation, degree modifiers, capitalisation, punctuation and contrastive clauses rather than just summing word scores.

Stringy::of('The food is good.')->sentimentScore(); // 0.4404
Stringy::of('The food is not good.')->sentimentScore(); // -0.3412
Stringy::of('The food is GOOD!')->sentimentScore(); // amplified by caps and "!"

sentimentLabel() // positive, negative or neutral
sentiment() // positive, negative and neutral proportions plus the compound score
sentimentBySentence() // each sentence scored separately, with a `sentence` key

sentimentScore() returns the compound score, normalised between -1 and 1. sentimentLabel() treats >= 0.05 as positive and <= -0.05 as negative.

Configuring the Lexicon

The bundled lexicon is a curated list of common sentiment bearing words rather than the full 7,500 entry VADER lexicon, which keeps the package light. In config/stringy.php you can point lexicon at a PHP file returning word => valence pairs (on a -4 to +4 scale) to replace the list entirely, or merge in domain terms with additions. Degree modifiers (boosters) work the same way.

'sentiment' => [
    'lexicon' => null,
    'additions' => [
        'downtime' => -2.4,
        'shipped' => 1.6,
    ],
],

'boosters' => [
    'lexicon' => null,
    'additions' => [
        'wildly' => 0.293,
    ],
],

A few things worth knowing:

  • Negation only reaches back three words, so "I do not think it was good" scores positive.
  • Coverage is only as good as the lexicon, so domain vocabulary is worth adding via additions.
  • Syllables are counted with a vowel-group heuristic, so individual words are occasionally off by one. The formulas average over the whole text, which washes this out for anything longer than a sentence or two.
  • Type-token ratio falls naturally as texts get longer, so only compare samples of similar length.

Model Concerns

Sometimes in our apps we have models that have similar concerns. We use traits to handle these, below are concerns we find commonly used in many applications.

CanAccessFeatures

A simple feature wrapper tool.

Config example:
You can run with Global or User based features.

[
    // Global based
    // 'portal' => env('FEATURE_PORTAL', false),

    // User based
    // 'portal' => [
    //     'state' => env('FEATURE_PORTAL', false),
    //     'users' => env('FEATURE_PORTAL_USERS', [])
    //],
]

To check you can easily check for access with $user->hasFeatureAccess($key)

DatabaseSearchable

Provides the following methods:

search($string) // Search all model columns for a match

HasCachedValues

Provides the following methods:

cacheIdentifier($string) // creates a custom identifier for a model item you wish to cache
clearCachedValues() // relies on a $caches property to be set identifying any strings used in the above method

Observable

Provides the following methods:

bootObservable() // Enables auto-registering of any Observers for the model

HasLocking

A model locking trait that prevents multiple users from editing the same record simultaneously.

Features:

  • Lock timeout based on 15-minute inactivity (no updates to updated_at)
  • Session-based locking to prevent same user on different machines from bypassing locks
  • Throws ModelLockedException when attempting to edit a locked model

Provides the following methods:

lock() // Lock the model for editing by the current user/session
unlock() // Unlock the model
isLocked() // Check if the model is currently locked
isLockedByCurrentUser() // Check if the model is locked by the current user/session
getLockOwner() // Get the user who has locked the model

Blade Directives

Support registers a handful of Blade directives for common view needs.

@feature('portal') // render the block only if the current user has access to the feature
    ...
@endfeature

@version // output the app version, the same value as app_version()

@docs // add a floating link to /docs (outside of production)

@session($nonce) // output javascript_session_data() for window.app.session

@feature checks request()->user()->hasFeatureAccess($key), so it should only be used where a user is authenticated.

Macros

Request

request()->routeIsWith('posts.show', ['post' => $post]) // match a route name and its parameters against the current URL
request()->routeIsWith(['posts.show', 'post' => $post]) // the same, as a single array
request()->routeIsWith('posts.*') // wildcards fall back to routeIs()

Collection

toObject() // convert the collection to a plain object
paginate($perPage, $page = null, $pageName = 'page') // paginate a collection with a LengthAwarePaginator
sortByDate($column = 'created_at') // sort by a date column, oldest first
sortByDateDesc($column = 'created_at') // sort by a date column, newest first
chunkBy($column = 'created_at') // group items by the unique values of a column

Routes

Support registers a few routes for you. Each page is standalone, so it doesn't depend on your app's layout, and follows the system light or dark preference.

Up

/up is a simple page confirming the application is running, handy for uptime checks.

Errors

/errors is a default error page, which can be used for Cloudflare's custom error pages.

Docs

/docs renders every file in your app's docs directory, along with your CHANGELOG.md, as a single page with a sidebar for each section and a link to /docs/api. Markdown is rendered and MermaidJS diagrams are supported. This route is not registered in staging or production. Pair it with the @docs directive to add a link to it from your app.

Commands

Cloudflare Purge

Purge the Cloudflare cache for a given zone.

php artisan cloudflare:purge {zone} {email} {key}