View file core/exfm.class.php

File size: 2.29Kb
<?php
/**
 Music search engine 1.0.0
 Copyright (C) 2012 softwarefreak <softwarefreak89@gmail.com>
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @package Music Search Engine
 * @version 1.0.0
 * @copyright Copyright (C) 2012 softwarefreak <softwarefreak89@gmail.com>
 * @link http://www.musicoxplore.com
 */
class Exfm {
	public $appName = 'Music Search Engine';
	public $appVersion = '1.0.0';
	public $q;
	public $start;
	public $data;
	protected $_searchBase = 'http://ex.fm/api/v3/song/search';
	protected $_json;
	protected $_reqUrl;
	protected $_ex = array('MISSING_PARAM' => 'Missing parameter search query', 'NO_VALID_INT' => 'A valid integer was not supplied', 'JSON_ERROR' => 'Unable to decode json', 'NOT_FOUND' => 'No results were found');

	public function __construct($q, $start) {
		if (empty($q)) {
			throw new Exception($this -> _ex['MISSING_PARAM']);
		}
		$this -> q = $q;
		if (!is_int($start)) {
			throw new Exception($this -> _ex['NO_VALID_INT']);
		}
		$this -> start = $start;
		$this -> make();
		$this -> load();
		$this -> parse();
	}

	protected function make() {
		$this -> _reqUrl = sprintf('%s/%s?start=%d', $this -> _searchBase, urlencode($this -> q), $this -> start);
	}

	protected function load() {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this -> _reqUrl);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$this -> _json = curl_exec($ch);
		if (!$this -> _json) {
			throw new Exception(curl_error($ch));
		}
		curl_close($ch);
		unset($ch);
	}

	protected function parse() {
		$this -> data = json_decode($this -> _json);
		if (is_null($this -> data)) {
			throw new Exception($this -> _ex['JSON_ERROR']);
		}
		if ($this -> data -> total == 0) {
			throw new Exception($this -> _ex['NOT_FOUND']);
		}
	}

}