Skip to content

Commit

Permalink
Reduce keywordPos lines
Browse files Browse the repository at this point in the history
  • Loading branch information
iranianpep committed Jul 18, 2017
1 parent 87ab333 commit 75849f8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/Botonomous/utility/MessageUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,10 @@ public function keywordPos(array $keywords, $message)
}

foreach ((new ArrayUtility())->sortArrayByLength($keywords) as $keyword) {
$result = preg_match_all("/\b{$keyword}\b/", $message, $matches, PREG_OFFSET_CAPTURE);

if ($result && !empty($matches[0])) {
foreach ($matches[0] as $match) {
// check if the keyword does not overlap with one of the already found
if ($this->isPositionTaken($found, $match[1]) === false) {
$found[$keyword][] = $match[1];
}
foreach ((new StringUtility())->findPositionInString($keyword, $message) as $position) {
// check if the keyword does not overlap with one of the already found
if ($this->isPositionTaken($found, $position) === false) {
$found[$keyword][] = $position;
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions src/Botonomous/utility/StringUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,28 @@ public function findInString($toFind, $subject, $wordBoundary = true)
return preg_match($pattern, $subject) ? true : false;
}

/**
* @param $toFind
* @param $subject
* @param bool $wordBoundary
*
* @return mixed
*/
public function findPositionInString($toFind, $subject, $wordBoundary = true)
{
$pattern = $wordBoundary === true ? "/\b{$toFind}\b/" : "/{$toFind}/";
$result = preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);

$positions = [];
if ($result && !empty($matches[0])) {
foreach ($matches[0] as $match) {
$positions[] = $match[1];
}
}

return $positions;
}

/**
* Convert snake case to camel case e.g. admin_user becomes AdminUser.
*
Expand Down

0 comments on commit 75849f8

Please sign in to comment.