Developed with love by KnpLabs Hire us for your project!
32

UrlShortenerBundle

by mremi

Implementation of UrlShortener library for Symfony2

MremiUrlShortenerBundle

SensioLabsInsight

Build Status
Total Downloads
Latest Stable Version
Scrutinizer Code Quality
Code Coverage

This bundle implements the UrlShortener library for Symfony.

License

This bundle is available under the MIT license.

Prerequisites

This version of the bundle requires Symfony 2.8, 3.0 or newer.

For compatibility with Symfony 2.7 or earlier, please use 1.0.* versions of
this bundle.

Basic Docs

Installation

Installation is a quick 5 step process:

  1. Download MremiUrlShortenerBundle using composer
  2. Enable the Bundle
  3. Create your Link class (optional)
  4. Configure the MremiUrlShortenerBundle
  5. Update your database schema (optional)

Step 1: Download MremiUrlShortenerBundle using composer

Require mremi/url-shortener-bundle via composer:

php composer.phar require mremi/url-shortener-bundle

Note: if you are using Symfony 2.7 or earlier, please require ~1.0.0 version:

php composer.phar require mremi/url-shortener-bundle:~1.0.0

Composer will modify your composer.json file and install the bundle to your
project's vendor/mremi directory.

Step 2: Enable the bundle

Enable the bundle in the kernel:

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Mremi\UrlShortenerBundle\MremiUrlShortenerBundle(),
    );
}

Step 3: Create your Link class (optional)

The goal of this bundle is not to persist some Link class to a database,
but you can if you want just by following next instructions.
So if you don't need to do this, you can jump to the next step.

Your first job, then, is to create the Link class for your application.
This class can look and act however you want: add any properties or methods you
find useful. This is your Link class.

The bundle provides base classes which are already mapped for most fields
to make it easier to create your entity. Here is how you use it:

  1. Extend the base Link class from the Entity folder
  2. Map the id field. It must be protected as it is inherited from the parent class
  3. Add index on long_url column: Doctrine does not allow to specify index size in the mapping, so you have to write it manually in a migration class.

Note:

For now, only Doctrine ORM is handled by this bundle (any PR will be
appreciated :) ).

<?php
// src/Acme/UrlShortenerBundle/Entity/Link.php

namespace Acme\UrlShortenerBundle\Entity;

use Mremi\UrlShortenerBundle\Entity\Link as BaseLink;

class Link extends BaseLink
{
    /**
     * @var integer
     */
    protected $id;
}
<!-- src/Acme/UrlShortenerBundle/Resources/config/doctrine/Link.orm.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Acme\UrlShortenerBundle\Entity\Link"
            table="link">

        <id name="id" column="id" type="integer">
            <generator strategy="AUTO" />
        </id>

    </entity>
</doctrine-mapping>
<?php
// app/DoctrineMigrations/VersionYYYYMMDDHHIISS.php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

class VersionYYYYMMDDHHIISS extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // customize index size as you want...
        $this->addSql("CREATE INDEX idx_url_shortener_link_long_url ON link (long_url(20))");
    }

    public function down(Schema $schema)
    {
        $this->addSql("DROP INDEX idx_url_shortener_link_long_url ON link;");
    }

Step 4: Configure the MremiUrlShortenerBundle

Fow now, you just have to configure your Bit.ly username and password.

# app/config/config.yml
mremi_url_shortener:
    link_class: Mremi\UrlShortener\Model\Link

    providers:
        bitly:
            enabled:             true
            username:            your_bitly_username
            password:            your_bitly_password
            options:
                connect_timeout: 1
                timeout:         1

        google:
            enabled:             true
            api_key:             your_api_key
            options:
                connect_timeout: 1
                timeout:         1

Step 5: Update your database schema (optional)

If you configured the data storage (step 3), you can now update your database
schema.

If you want to first see the create table query:

$ app/console doctrine:schema:update --dump-sql

Then you can run it:

$ app/console doctrine:schema:update --force

Chain providers

One service allow you to shorten/expand URL, to use like this:

<?php

$linkManager   = $container->get('mremi_url_shortener.link_manager');
$chainProvider = $container->get('mremi_url_shortener.chain_provider');

$link = $linkManager->create();
$link->setLongUrl('http://www.google.com');

$chainProvider->getProvider('bitly')->shorten($link);

$chainProvider->getProvider('google')->expand($link);

Custom provider

You can add your own provider to the chain providers:

  1. Create a service which implements \Mremi\UrlShortener\Provider\UrlShortenerProviderInterface
  2. Add the tag mremi_url_shortener.provider
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="acme.custom_provider" class="Acme\YourBundle\Provider\CustomProvider">
            <tag name="mremi_url_shortener.provider" />
        </service>
    </services>
</container>

Test configured providers

You can now test the providers you configured with the following command line:

$ app/console mremi:url-shortener:test

Retrieve link

You can retrieve some links using these finders:

<?php

$linkManager = $container->get('mremi_url_shortener.link_manager');

$shortened = $linkManager->findOneByProviderAndShortUrl('bitly', 'http://bit.ly/ze6poY');

$expanded = $linkManager->findOneByProviderAndLongUrl('google', 'http://www.google.com');

If you configured the data storage (steps 3 & 5), finders look first in
database ; if the link exists then return it, otherwise an API call will be
done and link will be saved.

Else this will consume an API call.

Twig functions

You can also simply shorten/expand a URL from a twig file. It should be used
with caution if no data storage is configured, because it's not HTTP friendly.

{# src/Acme/YourBundle/Resources/views/index.html.twig #}

{{ mremi_url_shorten('bitly', 'http://www.google.com') }}
{{ mremi_url_expand('google', 'http://goo.gl/fbsS') }}

Profiler

If your are in debug mode (see your front controller), you can check in the web
debug toolbar the configured providers and some statistics from the current
HTTP request: number of requests per provider, consumed memory, request
duration...

Screenshot

Contribution

Any question or feedback? Open an issue and I will try to reply quickly.

A feature is missing here? Feel free to create a pull request to solve it!

I hope this has been useful and has helped you. If so, share it and recommend
it! :)

@mremitsme

The MIT License (MIT)

Copyright (c) 2013-2014 RĂ©mi Marseille <marseille.remi@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
mremi_url_shortener:
link_class: Mremi\UrlShortener\Model\Link
providers:
bitly:
enabled: false
username: ~
password: ~
options:
connect_timeout: 1
timeout: 1
google:
enabled: false
api_key: ~
options:
connect_timeout: 1
timeout: 1
  • Merge pull request #8 from borisceranic/master
    By mremi, 2 years ago
  • Clarify install instructions for different versions of Symfony
    By , 2 years ago
  • Merge pull request #7 from borisceranic/master
    By mremi, 2 years ago
  • Fix wrong factory type declaration
    By borisceranic, 2 years ago
  • Merge pull request #6 from borisceranic/master
    By mremi, 2 years ago
  • Add compatibility with Symfony 3
    By borisceranic, 2 years ago
  • Multiple expand/shorten arguments
    By mremi, 2 years ago
  • Fixed some CS
    By mremi, 3 years ago
  • Added php 5.6 and hhvm in travis file
    By mremi, 3 years ago
  • Fixed tearDown in unit tests
    By mremi, 4 years ago
  • Added Scrutinizer badges
    By mremi, 4 years ago
  • Removed client factory
    By mremi, 4 years ago
  • Added copyrights
    By mremi, 4 years ago
  • Moved the license to follow best practices
    By mremi, 4 years ago
  • Fixed test command due to providers update
    By mremi, 5 years ago
  • Added contribution section in README.md
    By mremi, 5 years ago
  • Added Symfony2 keyword to composer.json
    By mremi, 5 years ago
  • Fixed whitespace
    By mremi, 5 years ago
  • Used integer node to configure the Google's timeout option
    By mremi, 5 years ago
  • Used integer node to configure the Google's connect timeout option
    By mremi, 5 years ago
  • Used integer node to configure the Bitly's timeout option
    By mremi, 5 years ago
  • Used integer node to configure the Bitly's connect timeout option
    By mremi, 5 years ago
  • [BC break] Added providers node
    By mremi, 5 years ago
  • Saved link in finders if not exist
    By mremi, 5 years ago
  • Updated version of UrlShortener to ~1.0
    By mremi, 5 years ago
  • [BC break] Passed LinkInterface to providers and used finders in Twig extension
    By mremi, 5 years ago
  • Added links in profiling
    By mremi, 5 years ago
  • Added SensioLabsInsight widget in README.md
    By mremi, 5 years ago
  • Used existing variable
    By mremi, 5 years ago
  • Fixed phpdoc
    By mremi, 5 years ago