Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added function sortresults + support for file flags #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions workflows.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class Workflows {
private $path;
private $home;
private $results;
private $sortfield;
private $sortascending;

/**
* Description:
Expand Down Expand Up @@ -384,9 +386,10 @@ public function mdfind( $query )
*
* @param array - data to save to file
* @param file - filename to write the cache data to
* @param flags - file flags used for 'file_put_contents'
* @return none
*/
public function write( $a, $b )
public function write( $a, $b, $flags = 0 )
{
if ( file_exists( $b ) ):
if ( file_exists( $this->path.'/'.$b ) ):
Expand All @@ -402,10 +405,10 @@ public function write( $a, $b )

if ( is_array( $a ) ):
$a = json_encode( $a );
file_put_contents( $b, $a );
file_put_contents( $b, $a, $flags );
return true;
elseif ( is_string( $a ) ):
file_put_contents( $b, $a );
file_put_contents( $b, $a, $flags );
return true;
else:
return false;
Expand Down Expand Up @@ -480,4 +483,43 @@ public function result( $uid, $arg, $title, $sub, $icon, $valid='yes', $auto=nul
return $temp;
}

/**
* Description:
* Helper function that sorts the results by given field and sort direction.
* Possible fields: uid, arg, title, subtitle, icon, valid, autocomplete, type
*
* @param $field - the field that will be used to sort the current array of results, defaults to 'title'
* @param $ascending - sort direction, defaults to true
* @return array - sorted array or false in case the given field is not allowed
*/
public function sortresults( $field='title', $ascending=true )
{
// abort in case the field is not allowed
$allowed = array("uid", "arg", "title", "subtitle", "icon", "valid", "autocomplete", "type");
if (!in_array($field, $allowed)):
return false;
endif;

$this->sortfield = $field;
$this->sortascending = $ascending;
uasort($this->results, function ($a, $b) {
$c = $a[$this->sortfield];
$d = $b[$this->sortfield];

if ( $c === $d ) {
return 0;
}
if ($this->sortascending) {
return ($c > $d) ? 1 : -1;
} else {
return ($c > $d) ? -1 : 1;
}
});

unset($this->sortfield);
unset($this->sortascending);

return $this->results;
}

}