<?php

/**
 * Validator class for page slugs.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 - 2013 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfValidatorPageSlug Class
 *
 * Custom validator to test availability of a page slug.
 *
 * @package clearFusionCMS
 */
class cfValidatorPageSlug extends flFormValidator {

	/**
	 * The current page slug if any.
	 *
	 * @var string
	 */
	private $current;

	/**
	 * The content object.
	 *
	 * @var cfContent
	 */
	private $ctnt;

	/**
	 * The parent node.
	 *
	 * @var int
	 */
	private $parent;

	/**
	 * Construct the object.
	 *
	 * @param cfContent $ctnt The content object.
	 * @param int $parent The parent of the page.
	 * @param string $current The current slug.
	 */
	function __construct($ctnt, $parent, $current = null) {
		parent::__construct(null, __("The slug '{current}' has already been used.", 'cfBackend'));
		$this->current = $current;
		$this->ctnt = $ctnt;
		$this->parent = $parent;
	}

	/**
	 * Validate the element against the validator.
	 *
	 * @param flFormElement $elem The element to validate.
	 * @return bool true if the element is valid else false.
	 */
	function validate($elem) {
		parent::validate($elem);

		if($this->current !== null && $this->current == $elem->getValue())
			return true;

		return !$this->ctnt->hasChildSlug($this->parent, $elem->getValue());
	}

	/**
	 * Get the client side rule for validation.
	 *
	 * @return array [0] The string holding the rule information for use with fusionLib.validation.js
	 * [1] true to use ajax or false, if false is returned instead of an array then no client side validation is done
	 */
	function getClientRule() {
		return array('', true);
	}
}