Code Monkey home page Code Monkey logo

open-graph's Introduction

Open Graph Builder

Build Status Monthly Downloads Version GitHub license

Library that assists in building Open Graph meta tags.

Installation

Add chriskonnertz/open-graph to composer.json with a text editor:

"chriskonnertz/open-graph": "~2"

Or via a console:

composer require chriskonnertz/open-graph

In the future use composer update to update to the latest version of Open Graph Builder.

This library requires PHP >=7.0.

Framework Support

Laravel >=5.5 can auto-detect this package so you can ignore this section. In Laravel 5.0-5.4 you have to edit your config/app.php config file. You can either add an alias to the object so you can create a new instance via new OpenGraph() ...

'aliases' => [
    ...
    'OpenGraph' => 'ChrisKonnertz\OpenGraph\OpenGraph',
],

...or an alias to the facade (this is what happens in Laravel >=5.5 via package auto-discovery) so you do not have to create the instance by yourself but you can access it via pseudo-static methods. If you choose this path you also have to add the service provider to the config file:

'aliases' => [
    ...
    'OpenGraph' => 'ChrisKonnertz\OpenGraph\OpenGraphFacade',
],

...

'providers' => [
    ...
    'ChrisKonnertz\OpenGraph\OpenGraphServiceProvider',
],

If you need to reset the underlying instance of the facade (the OpenGraph object), call OpenGraph::clear().

Introduction

Example:

$og = OpenGraph::title('Apple Cookie')
    ->type('article')
    ->image('http://example.org/apple.jpg')
    ->description('Welcome to the best apple cookie recipe never created.')
    ->url();

Render these tags in a template as follows:

{!! $og->renderTags() !!}

Providing Open Graph tags enriches web pages. The downside is some extra time to spend, because every model has its own way to generate these tags. It's also important to follow the official protocol. Read the documentation to learn more about the tags that are available and the values they support or check out examples. Please note that this implementation sticks to the specification of OGP.me and does not support the enhancements created by Facebook.

Add Tags And Attributes

Add Basic Tags

$og->title('Apple Cookie')
    ->type('article')
    ->description('A delicious recipe')
    ->url()
    ->locale('en_US')
    ->localeAlternate(['en_UK'])
    ->siteName('Cookie Recipes Website')
    ->determiner('an');

If no argument is passed to the url method the current URL is applied. Note that the environment variable APP_URL is considered if it is set. Furthermore, when executed via CLI, and APP_URL is not set, the domain will be localhost.

Note that DateTime objects will be converted to ISO 8601 strings.

Add Tags With Attributes

You may add image, audio or video tags and pass the basic value (the URL to the object) and an array of additional attributes.

$og->image($imageUrl, [
    'width'     => 300,
    'height'    => 200
]);

$og->audio($audioUrl, [
    'type'     => 'audio/mpeg'
]);

$og->video($videoUrl, [
    'width'     => 300,
    'height'    => 200,
    'type'      => 'application/x-shockwave-flash'
]);

Add Type Attributes

Some object types (determined by the type tag) have their own tags with attributes but not a basic tag. These are article, book and profile.

$og->article([
    'author'        => 'Jane Doe'
]);

$og->book([
    'author'        => 'John Doe'
]);

$og->profile([
    'first_name'    => 'Kim',
    'last_name'     => 'Doe'
]);

Add Attributes

Facebook supports more than just the basic object types. To add attributes for off-the-record object types you may use the attributes method.

Without custom validation rule:

$og->attributes('product', ['product:color' => 'red']);

With custom validation rule:

$og->attributes('product', ['product:color' => 'red'], ['product:color']);

The only validation this method performs is to check if all attribute names match with the list of attribute names.

Add A Tag Several Times

A property can have multiple values. Add the tag several times to achieve this effect.

$og->image('http://example.org/apple.jpg')
    ->image('http://example.org/tree.jpg');

Adding a basic tag a second time will override the value of the first tag. Basic tags must not exist several times.

Validation

If validation is enabled (default is disabled) adding tags will trigger validation. Validation is not covering the complete specification but some important parts. If validation fails the method will throw an exception.

Validation checks if tag values are legit and if attribute types are known.

Enable validation by method:

$og->validate();

By constructor:

$og = new OpenGraph(true);

Disable validation:

$og->validate(false);

Miscellaneous

Determine If A Tag Exists

$hasTitle = $og->has('title');

Remove A Tag From The List

$og->forget('title');

Remove All Tags From The List

$og->clear();

Add A Custom Tag

$og->tag('apples', 7);

To disable auto-prefixing pass a third parameter: $og->tag('apples', 7, false)

Get The Last Tag (By Name)

$tag = $og->lastTag('image');
$value = $tag['value'];

Tags are stored as arrays consisting of name-value-pairs.

Status

Status of this repository: Maintained. If you create an issue you will get a response usually within 48 hours.

open-graph's People

Contributors

chriskonnertz avatar fabriziocafolla avatar kalanaperera avatar samwalshnz avatar wast avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

open-graph's Issues

PHP 5.4 required?

First thing: awesome package! Exactly what i searched for!

Sad thing: the composer.json file says your package needs PHP 5.4 to work. I sadly don't have PHP 5.4 and was wondering if the code would probably also work with PHP 5.3.* ?

OpenGraph::convertDate may return not string

Method OpenGraph::convertDate has return type string, but can return parameter $date which not typed and not casted. So may be use typed parameter in this method or cast parameter to string in return statement.

PHP 8

Add support to PHP 8

REQUEST URI not set

Hello,

when running tests, from CLI, you can get: that REQUEST URI is unidetified.

At this string:$safeRequestURI = htmlentities(strip_tags(urldecode($_SERVER['REQUEST_URI'])));

is the 'isset()' here enoght? Or are there any other 'cirmustances' to avoid?

Thank you

Video with attribute leads to error

$og->video( 'https://www.youtube.com/embed/123', ['type' => 'text/html'] );

leads to

Attempted to call function "starts_with" from namespace "ChrisKonnertz\OpenGraph".

Semver support

Hello, have been a happy user of this package for 6 months or so however the latest commits were not backwards compatible.

Any chance of tagging a release and implementing semver?

renderTags method should not be escaped in templates

Hi,

Documentation says that we should use renderTags() method inside template like this {{ $og->renderTags() }} which I believe is not correct, at least for Laravel 5.1.

I'm new in Laravel, using 5.1 and I was able to render meta tags correctly only without escaping it like this:

{!! $og->renderTags() !!}

Maybe I'm wrong and missing something, if so let me know.

For now as I see It's just documentation problem, everything works well, thanks for this awesome package!

Service Provider Facade?

Have you considered throwing in an optional service provider facade thing? Some use cases of this open-graph would benefit from there being one of those things.

composer.json

Bitte in der Datei composer.json folgende zeile 28 bearbeiten "OpenGraph' => 'ChrisKonnertz\OpenGraph\OpenGraphFacade'" in "OpenGraph' => 'ChrisKonnertz\OpenGraph\OpenGraph".

Leider wird sonst dieses Modul von Laravel nicht direkt angesprochen und muss manuell bearbeitet werden.

Generates og:article:XXX rather than article:XXX

...which therefore fails Facebook's validation (https://developers.facebook.com/tools/debug/og/object/).

and seemingly is against the spec - http://ogp.me/#type_article

Can you confirm that 'og:article:XXX' is definitely right?

Here's the relevant validation output:

Warnings That Should Be Fixed
Extraneous Property Objects of this type do not allow properties named 'og:article:published_time'.
Extraneous Property Objects of this type do not allow properties named 'og:article:modified_time'.
Parser Mismatched Metadata The parser's result for this metadata did not match the input metadata. Likely, this was caused by the data being ordered in an unexpected way, multiple values being given for a property only expecting a single value, or property values for a given property being mismatched. Here are the input properties that were not seen in the parsed result: 'og:article:published_time, og:article:modified_time'

Warning OpenGraph::$title is deprecated

Hello,

I've had this alert for some time now:

Creation of dynamic property ChrisKonnertz\OpenGraph\OpenGraph::$title is deprecated in /var/www/html/vendor/laravel/framework/src/Illuminate/Session/Store.php on line 117

Note that I don't use this property in my code ...

chriskonnertz/open-graph 2.0
PHP 8.2.5
Laravel 9.52.15

Cordialy

title not found

it doesn't work in laravel 5.5. Getting this error:

Call to undefined method ChrisKonnertz\OpenGraph\OpenGraphFacade::title()

Not working

$og = new ChrisKonnertz\OpenGraph\OpenGraph();

$og->title('Apple Cookie')
    ->type('article')
    ->image('http://example.org/apple.jpg')
    ->description('Welcome to the best apple cookie recipe never created.')
    ->url();

$res = $og->renderTags();

print_r($res);
echo $res;
var_dump($res); //string(0) ""

The result variable is empty. Nothing is output. Why is that?
ps php 7.2

asset($imageFile) function

By accident i pass wrong image string to image() method and get strange error:
Call to undefined function ChrisKonnertz\OpenGraph\asset()

I found several asset function calls in OpenGraph class:

$imageFile = asset($imageFile);

$audioFile = asset($audioFile);

Fast investigation gave me no traces of this function. Can somebody satisfy my curiosity?

Setting description can generate an invalid string

Since it uses substr rather than mb_substr a multibyte character spanning the max length boundary will get turned into an invalid character.

Luckily the fix is trivial, but it would be nice to have a test case added too :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.