Skip to content

Instantly share code, notes, and snippets.

@vades
Last active May 21, 2019 06:30
Show Gist options
  • Save vades/071a312d26e1875e70a9014cd9c9db6b to your computer and use it in GitHub Desktop.
Save vades/071a312d26e1875e70a9014cd9c9db6b to your computer and use it in GitHub Desktop.
PHP class to detect a language

PHP Class to detect a language from url, session, cookie and browser

This class detects a language from the url, session, cookie and browser and then sets a current one.

LanguageSwitch.php

<?php

namespace Vades\Language;

class LanguageSwitch {
  /**
    * Language property
    * @var string
    */
  protected $language;
  
  /**
    * Default language
    * @var string 
    */
  protected $default;
  
  /**
    * Supported languages
    * @var type 
    */
  protected $supported = array();
  
  /**
    * Language from url
    * @var string 
    */
  protected $url;
  
  /**
    * Language from session
    * @var string 
    */
  protected $session;
  
  /**
    * Language from cookie
    * @var string 
    */
  protected $cookie;
  
  /**
    * Language from browser
    * @var string 
    */
  protected $browser;

  /**
    * Inject the config into constructor
    * 
    * @param array $config
    * @return void
    */
  public function __construct($config = array()) {
      $this->init($config);
  }

  /**
    * Init class properties
    * 
    * @param array $config
    * @return void
    */
  public function init($config) {
      foreach ($config as $key => $value) {
          if (property_exists($this, $key)) {
              $this->$key = $value;
          }
      }
  }

  /**
    * Get language
    * 
    * @return string
    */
  public function get() {
      if (!$this->language) {
          $this->language = $this->getDefault();
      }
      return $this->language;
  }

  /**
    * Set language
    * 
    * @return string
    */
  public function setLanguage($language) {
      if ($this->isSupported($language)) {
          $this->language = $language;
      }
  }
  
  /**
    * Get default language
    * 
    * @return string
    */
  public function getDefault() {
      return $this->default;
  }
  /**
    * Get supported languages
    * 
    * @return array
    */
  public function getSupported() {
      return (array)$this->supported;
  }
  
  /**
    * Check if language is supported
    * 
    * @param string $language
    * @return boolean
    */
  public function isSupported($language) {
      if (!in_array($language, $this->getSupported())) {
          return false;
      }
      return true;
  }

  /**
    * Detect language from url
    * 
    * @param string $language
    * @return \Vades\Language\LanguageSwitch
    */
  public function fromUrl($language = null) {
      $language = $language ? $language : $this->url;
      $this->setLanguage($language);
      return $this;
  }

  /**
    * Detect language from session
    * 
    * @param string $language
    * @return \Vades\Language\LanguageSwitch
    */
  public function fromSession($language = null) {
      $language = $language ? $language : $this->session;
      $this->setLanguage($language);
      return $this;
  }

  /**
    * Detect language from cookie
    * 
    * @param string $language
    * @return \Vades\Language\LanguageSwitch
    */
  public function fromCookie($language = null) {
      $language = $language ? $language : $this->cookie;
      $this->setLanguage($language);
      return $this;
  }

  /**
    * Get language from browser
    * 
    * @param string $language
    * @return \Vades\Language\LanguageSwitch
    */
  public function fromBrowser($language = null) {
      $language = $language ? $language : $this->browser;
      $this->setLanguage($language);
      return $this;
  }
}

config.php

<?php
/**
 * LanguageSwitch configuration file
 */
return array(
    /**
     * Default language
     */
    'default' => 'en',
    
    /**
     * Supported languages
     */
    'supported' => array('en','de','fr','es','it'),
);

Usage

Include class and config into your code

require_once 'LanguageSwitch.php';
$cfg = require_once 'config.php';

Initialize the LanguageSwitch

$switch = new LanguageSwitch(array(
    'default' => $cfg['default'],
    'supported' => $cfg['supported'],
    'url' => $lang_from_url ,
    'session' => $lang_from_session,
    'cookie' => $lang_from_ucookie,
    'browser' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)
));

Use it with method chaining

 $lang = $switch->fromUrl()
        ->fromSession()
        ->fromCookie()
        ->fromBrowser()
        ->get();

Example

<?php
 
  require_once '../src/Vades/Language/LanguageSwitch.php';
  use \Vades\Language\LanguageSwitch;

  $cfg = require_once '../src/Vades/Language/config.php';

  // Start session
  if (strlen(session_id()) < 1) {
      session_start();
      $_SESSION['lang'] = 'de';
  }
  // Set cookie
  setcookie('lang', 'fr', time()+60);

  // Initialize the language switch
  $switch = new LanguageSwitch(array(
      'default' => $cfg['default'],
      'supported' => $cfg['supported'],
      'url' => (isset($_GET['lang']) ? $_GET['lang'] : null) ,
      'session' => (isset($_SESSION['lang']) ? $_SESSION['lang'] : null),
      'cookie' => (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : null),
      // Extract the two digit language code from the http headers 
    'browser' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)
  ));

  $lang = $switch->fromUrl()
          ->fromSession()
          ->fromCookie()
          ->fromBrowser()
          ->get();

  var_dump($switch,$lang);

Source

VADES Git

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment