Write a class ‘Skill’ that handles any function which starts with ‘has_’ keyword return function ‘exist’ and any other function that starts with any word that should return ‘not exist’ and checking a property if it ends with ‘_CT’ return md5 encryption for property otherwise return without encryption.
I have used magic functions and object-oriented programming.
Below are the files with the code for class Skill and test cases:
Skill.php
<?php declare(strict_types=1);
namespace Exam;
class Skill
{
public function __call($name, $arguments)
{
if (strpos($name, 'has_') === 0) {
return 'exist';
} else {
return 'not exist';
}
}
public function __get($name)
{
if (substr($name, -3) === '_CT') {
return md5($name);
} else {
return 'not exist';
}
}
public function __toString()
{
return 'Skill object';
}
public function __set($name, $value)
{
$this->$name = $value;
}
public function __invoke($args)
{
return array_sum($args);
}
}
SkillTest.php
<?php
use CoalitionExamSkill;
use PHPUnitFrameworkTestCase;
class SkillTest extends TestCase
{
public function testHasFunctionExists(): void
{
$skill = new Skill();
$function = 'has' . $this->generateRandomString(5);
$this->assertTrue($skill->$function(), 'success');
}
public function testHasPropertyExists(): void
{
$skill = new Skill();
$property = $this->generateRandomString(7) . '_CT';
$this->assertTrue($skill->$property == md5($property), 'success');
}
public function testHasAnyPropertyExists(): void
{
$skill = new Skill();
$property = $this->generateRandomString(7);
$this->assertFalse($skill->$property == md5($property), 'success');
}
public function testObjectAsString(): void
{
$skill = new Skill();
$this->assertTrue( strpos($skill, 'CT') !== false, 'success');
}
public function testSetSkillLanguage(): void
{
$skill = new Skill();
$skill->language = 'PHP';
$this->assertTrue( $skill->language === 'PHP', 'success');
}
public function testInvoke(): void
{
$skill = new Skill();
$this->assertEquals(10, $skill([3,7]));
}
private function generateRandomString($length = 10): string
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}
When I run PHPUnit tests, I am getting 2 failures.
There were 2 failures:
1)
SkillTest::testHasFunctionExists
success
Failed asserting that ‘not exist’ is true.
C:xampphtdocsRizeen-CTtestsSkillTest.php:12
-
SkillTest::testObjectAsString
success
Failed asserting that false is true.
C:xampphtdocsRizeen-CTtestsSkillTest.php:34
FAILURES!
Tests: 6, Assertions: 6, Failures: 2.
I tried using assertFalse(), but the issue still persists.