Skip to content

Instantly share code, notes, and snippets.

@ahsio
Created January 28, 2017 22:32
Show Gist options
  • Save ahsio/8738a4045957d1627bbf621308e7b039 to your computer and use it in GitHub Desktop.
Save ahsio/8738a4045957d1627bbf621308e7b039 to your computer and use it in GitHub Desktop.
<?php
class Palindrome
{
/**
* @param string $str
*
* @return bool
*
* @throws Exception
*/
public static function isPalindrome($str)
{
if (! is_string($str) || empty($str)) {
throw new \Exception(
sprintf('Bad input! Non-empty string expected! %s given', $str)
);
}
$cleanedStr = strtolower(
preg_replace("/[^a-zA-Z]+/", "", $str)
);
$strArray = str_split($cleanedStr);
return $strArray === array_reverse($strArray);
}
}
class PalindromeTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider palindromes
*/
public function testIsPalindromeOnSuccess($str)
{
$this->assertTrue(Palindrome::isPalindrome($str));
}
/**
* @dataProvider nonPalindromes
*/
public function testIsPalindromeOnFailure($str)
{
$this->assertFalse(Palindrome::isPalindrome($str));
}
/**
* @expectedException \Exception
*
* @dataProvider badData
*/
public function testIsPalindromeWhenItThrowsAnException($str)
{
Palindrome::isPalindrome($str);
}
public function palindromes()
{
return [
'palindrome_1' => ['noel sees leon'],
'palindrome_2' => ['Noel Sees Leon'],
];
}
public function nonPalindromes()
{
return [
'non-palindrome_1' => ['String that s not a palindrome'],
'non-palindrome_2' => ['null'],
];
}
public function badData()
{
return [
'bad_data_empty' => [''],
'bad_data_null' => [null],
'bad_data_-1' => [-1]
];
}
}
// For testing purposes (do not submit uncommented):
echo Palindrome::isPalindrome('Noel sees Leon.'). "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment