public function init($param = 0)
 {
     if (curry($_POST['pst'])) {
         if (!curry($_SESSION['userInformation'])) {
             echo json_encode(['code' => 0, 'msg' => 'You need to be logged in to logged out!', 'showTime' => 3000]);
             exit;
         } else {
             unset($_SESSION['userInformation']);
             unset($_COOKIE['gpl']);
             setcookie("gpl", "NOTSET", time() - 1, "/");
             if (curry($_SESSION['userInformation'])) {
                 echo json_encode(['code' => 0, 'msg' => 'Something went wrong while logging you out.', 'showTime' => 3000]);
             } else {
                 echo json_encode(['code' => 1]);
             }
         }
         exit;
     } else {
         if (!curry($_SESSION['userInformation'])) {
             header("Location: /Planningsysteem/login/?e=rl");
             exit;
         } else {
             unset($_SESSION['userInformation']);
             unset($_COOKIE['gpl']);
             setcookie("gpl", "NOTSET", time() - 1, "/");
             if (curry($_SESSION['userInformation'])) {
                 header("Location: /Planningsysteem/login/?e=f");
                 exit;
             } else {
                 header("Location: /Planningsysteem/login/?e=s");
                 exit;
             }
         }
     }
 }
Exemple #2
0
function test_curry()
{
    $a = function ($a, $b) {
        return $a + $b;
    };
    $add5 = curry($a, 5);
    return is_identical($add5(10), 15);
}
 public function init($param = 0)
 {
     if (curry($_SESSION['userInformation'])) {
         $this->_userInfo = $_SESSION['userInformation'];
     } else {
         header("Location: /Planningsysteem/login/");
     }
     if (curry($_POST['oldPassword']) && curry($_POST['newPassword']) && curry($_POST['repeatNewPassword'])) {
         if (empty($_POST['oldPassword'])) {
             echo json_encode(['code' => 0, 'msg' => 'Old password may not be empty.', 'showTime' => 2000]);
             exit;
         }
         if (empty($_POST['newPassword'])) {
             echo json_encode(['code' => 0, 'msg' => 'New password may not be empty.', 'showTime' => 2000]);
             exit;
         }
         if (empty($_POST['repeatNewPassword'])) {
             echo json_encode(['code' => 0, 'msg' => 'Repeated new password may not be empty.', 'showTime' => 2000]);
             exit;
         }
         if ($_POST['newPassword'] != $_POST['repeatNewPassword']) {
             echo json_encode(['code' => 0, 'msg' => 'Passwords do not match!', 'showTime' => 2000]);
         }
         if ($_POST['newPassword'] == $_POST['oldPassword']) {
             echo json_encode(['code' => 0, 'msg' => 'Old password and your new password may not be the same!', 'showTime' => 3000]);
         }
         if (strlen($_POST['newPassword']) < 5) {
             echo json_encode(['code' => 0, 'msg' => 'New password may not be shorter than 5 characters!', 'showTime' => 2000]);
         }
         if (strlen($_POST['repeatNewPassword']) < 5) {
             echo json_encode(['code' => 0, 'msg' => 'Repeated new password may not be shorter than 5 characters!', 'showTime' => 2000]);
         }
         $this->_userModel = $this->model('user');
         if ($this->_userModel->verifyPasswordByUserInfo($this->_userInfo, $_POST['oldPassword'])) {
             if ($this->_userModel->updatePasswordByUserID($this->_userInfo->werknemer_id, $_POST['newPassword'])) {
                 unset($_SESSION['userInformation']);
                 if (curry($_COOKIE['gpl'])) {
                     unset($_COOKIE['gpl']);
                     setcookie("gpl", "NOTSET", time() - 1, "/");
                 }
                 echo json_encode(['code' => 1]);
             } else {
                 echo json_encode(['code' => 0, 'msg' => 'Failed to update your password.', 'showTime' => 2000]);
             }
         } else {
             echo json_encode(['code' => 0, 'msg' => 'Incorrect (old) password entered!', 'showTime' => 3000]);
         }
     } else {
         if ($this->isLoggedIn()) {
             $this->view('head', ['title' => 'Wachtwoord Veranderen - GrouPlaylist']);
             $this->view('header', ['loggedInUserInfo' => $_SESSION['userInformation']]);
             $this->view('changePassword', ['loggedInUserInfo' => $_SESSION['userInformation']]);
             $this->view('footer', ['loggedInUserInfo' => $_SESSION['userInformation']]);
         } else {
             header("Location: /Planningsysteem/login/");
         }
     }
 }
 public function init($param = 0)
 {
     if (!curry($_SESSION['userInformation'])) {
         header("Location: /Planningsysteem/login/");
     }
     $this->view('head', ['title' => 'Home | Planningsysteem']);
     $this->view('header', ['loggedInUserInfo' => $_SESSION['userInformation']]);
     $this->view('footer', ['loggedInUserInfo' => $_SESSION['userInformation']]);
 }
Exemple #5
0
 public function test_curry_function_with_arity_arg()
 {
     $strtime = curry('microtime');
     $floattime = call_user_func(curry('microtime', 2), true);
     $strstrWithBrianAndColon = call_user_func(call_user_func(curry('strstr', 3), 'brian:scaturro'), ':');
     $this->assertTrue(is_string($strtime()));
     $this->assertTrue(is_float($floattime()));
     $this->assertEquals('brian', $strstrWithBrianAndColon(true));
 }
Exemple #6
0
/**
 * @param $fn
 * @return \Closure
 */
function _cached_curry($fn)
{
    static $cache = [];
    if (isset($cache[$fn])) {
        return $cache[$fn];
    } else {
        return $cache[$fn] = curry($fn);
    }
}
 /**
  * @test
  */
 public function it_tests_curry()
 {
     $add = function ($a, $b) {
         return $a + $b;
     };
     $threeParams = function ($a, $b, $c) {
         return $a + $b + $c;
     };
     $addTwo = curry($add, 2);
     $addFive = curry($threeParams, 5);
     $this->assertEquals(5, $addTwo(3));
     $this->assertEquals(10, $addFive(3, 2));
 }
 public function init($param = 0)
 {
     if (curry($_SESSION['userInformation'])) {
         header("Location: /Planningsysteem/");
         exit;
     }
     if (curry($_SESSION['tmpUserInformation'])) {
         $this->_userInfo = $_SESSION['tmpUserInformation'];
     } else {
         // e = you already updated
         header("Location: /Planningsysteem/login/?e=yau");
         exit;
     }
     if (curry($_POST['password']) && curry($_POST['repeatPassword'])) {
         $this->_userModel = $this->model('user');
         if ($_POST['password'] != "") {
             $this->_password = $this->_userModel->encodeValueByString($_POST['password']);
         } else {
             echo json_encode(['code' => 0, 'msg' => 'Password cannot be empty!']);
             exit;
         }
         if ($_POST['repeatPassword'] != "") {
             $this->_repeatPassword = $this->_userModel->encodeValueByString($_POST['repeatPassword']);
         } else {
             echo json_encode(['code' => 0, 'msg' => 'Repeated Password cannot be empty!']);
             exit;
         }
         if ($this->_password != $this->_repeatPassword) {
             echo json_encode(['code' => 0, 'msg' => 'Passwords do not match!']);
             exit;
         }
         if ($this->_userModel->changePasswordByUserID($this->_userInfo->werknemer_id, $this->_password)) {
             if ($this->_userModel->setCustomPassword($this->_userInfo->werknemer_id)) {
                 unset($_SESSION['tmpUserInformation']);
                 echo json_encode(['code' => 1]);
             } else {
                 echo json_encode(['code' => 0, 'msg' => 'Failed to update your password.']);
             }
         } else {
             echo json_encode(['code' => 0, 'msg' => 'Failed to change password!']);
         }
     } else {
         $this->view('head', ['title' => 'Set Password | ' . $this->_userInfo->username]);
         $this->view('header', ['loggedInUserInfo' => false]);
         $this->view('firstLogin', ['userInfo' => $this->_userInfo]);
         $this->view('footer', ['loggedInUserInfo' => false]);
     }
 }
 /**
  *
  * This function checks if someone is logged in, if not, he will be redirected
  * to the login page.
  */
 public function isLoggedIn($adminRequired = 0)
 {
     if (curry($_SESSION['userInformation'])) {
         if ($adminRequired) {
             if ($_SESSION['userInformation']->is_admin) {
                 return true;
             } else {
                 return false;
             }
         } else {
             return true;
         }
     } else {
         header("Location: /Planningsysteem/login/");
     }
 }
 public function init($param = 0)
 {
     if ($this->isLoggedIn(true)) {
         if (curry($_POST['customerName'])) {
             $this->_userModel = $this->model('user');
             if ($this->_userModel->createCustomer($_POST['customerName'], $_POST['customerAdres'], $_POST['customerPhone'], $_POST['customerPostal'], $_POST['customerEmail'], $_POST['customerContact'], $_POST['customerPlaats'])) {
                 echo json_encode(['code' => 1]);
             } else {
                 echo json_encode(['code' => 0, 'msg' => 'Kon gebruiker niet aanmaken.']);
             }
         } else {
             $this->view('head', ['title' => 'Klant Aanmaken - Planningsysteem']);
             $this->view('header', ['loggedInUserInfo' => $_SESSION['userInformation']]);
             $this->view('createCustomer', ['userInfo' => $_SESSION['userInformation']]);
             $this->view('footer', ['loggedInUserInfo' => $_SESSION['userInformation']]);
         }
     } else {
         header("Location: /Planningsysteem/");
     }
 }
    public function send(EmailMessage $message, $data = [])
    {
        $recipient = function (Email $email) {
            return $email->getValue();
        };
        $commaSeparated = curry('implode', ', ');
        $formatRecipients = compose($commaSeparated, map($recipient));
        $recipientsString = $formatRecipients($message->recipients);
        // Append the original recipients to the end of the email for debug purposes
        $message->body .= <<<EOT


------------- DEBUG INFO ----------------

Original recipients: {$recipientsString}

----------------------------------------------
EOT;
        // Alter the recipients to send them all to the dev mailbox
        $message->recipients = [$this->destinationEmail];
        // Send the email using the normal mailer
        $this->mailer->send($message, $data);
    }
Exemple #12
0
/**
 * Converts an array to an associative array, based on the result of calling `$fn`
 * on each element, and grouping the results according to values returned.
 * Note that `$fn` should take an item from the list and return a string.
 * ```php
 * $persons = [
 *     ['name' => 'foo', 'age' => 11],
 *     ['name' => 'bar', 'age' => 9],
 *     ['name' => 'baz', 'age' => 16],
 *     ['name' => 'zeta', 'age' => 33],
 *     ['name' => 'beta', 'age' => 25]
 * ];
 * $phase = function($person) {
 *     $age = $person['age'];
 *     if ($age < 13) return 'child';
 *     if ($age < 19) return 'teenager';
 *     return 'adult';
 * };
 * groupBy($phase, $persons);
 * // [
 * //  'child' => [['name' => 'foo', 'age' => 11], ['name' => 'bar', 'age' => 9]],
 * //  'teenager' => [['name' => 'baz', 'age' => 16]],
 * //  'adult' => [['name' => 'zeta', 'age' => 33], ['name' => 'beta', 'age' => 25]]
 * // ]
 * ```
 *
 * @signature (a -> String) -> [a] -> {String: a}
 * @param  callable $fn
 * @param  array $list
 * @return array
 */
function groupBy()
{
    $groupBy = function ($fn, $list) {
        return reduce(function ($result, $item) use($fn) {
            $index = $fn($item);
            if (!isset($result[$index])) {
                $result[$index] = [];
            }
            $result[$index][] = $item;
            return $result;
        }, [], $list);
    };
    return apply(curry($groupBy), func_get_args());
}
Exemple #13
0
/**
 * Computes the product of an array of numbers.
 * ```php
 * product([1, 2, 3, 4]) // 24
 * product([]) // 1
 * ```
 *
 * @signature [Number] -> Number
 * @param  array $numbers
 * @return int|float
 */
function product()
{
    return apply(curry(function ($numbers) {
        return reduce(multiply(), 1, $numbers);
    }), func_get_args());
}
Exemple #14
0
// Grouping syntax
function __()
{
    return array_merge(['grouped' => true], func_get_args());
}
call_user_func(function () {
    $interpret = null;
    $call = curry(function (array $env, $f, $arg) use(&$interpret) {
        return op($f, $interpret($env, $arg));
    });
    $chain = curry(function (array $env, array $calls) use($call) {
        return array_reduce(array_diff_key($calls, ['grouped' => '']), $call($env), function ($x) {
            return $x;
        });
    });
    $plumb = curry(function (array $env, array $expr, $arg) use($chain) {
        return $expr ? $chain(array_merge([$arg], $env), $expr) : $arg;
    });
    $interpret = curry(function (array $e, $x) use($chain, $plumb) {
        // Assume ints and arrays are Plumb; anything else is PHP
        if (is_int($x)) {
            return $e[$x];
        }
        if (is_array($x)) {
            return isset($x['grouped']) ? $chain($e, $x) : $plumb($e, $x);
        }
        return $x;
    });
    // Interpret $f in an empty environment
    defun('plumb', $plumb([]));
});
Exemple #15
0
/**
 * Splits a string into chunks without spliting any group surrounded with some
 * specified characters. `$surrounders` is a string where each pair of characters
 * specifies the starting and ending characters of a group that should not be split.
 * ```php
 * $groups = chunks('(){}', ',');
 * $groups('1,2,(3,4,5),{6,(7,8)},9'); // ['1', '2', '(3,4,5)', '{6,(7,8)}', '9']
 *
 * $names = chunks('()""', ' ');
 * $names('Foo "Bar Baz" (Some other name)'); // ['Foo', 'Bar Baz', 'Some other name']
 * ```
 *
 * @signature String -> String -> String -> [String]
 * @param  string $surrounders
 * @param  string $separator
 * @param  sring $text
 * @return array
 */
function chunks()
{
    $chunks = function ($surrounders, $separator, $text) {
        // Let's assume some values to understand how this function works
        // surrounders = '""{}()'
        // separator = ' '
        // $text = 'foo ("bar baz" alpha) beta'
        $surrounders = map(slices(1), slices(2, $surrounders));
        // [['"'. '"'], ['{'. '}'], ['(', ')']]
        $openings = map(get(0), $surrounders);
        // ['"', '{', '(']
        $closings = map(get(1), $surrounders);
        // ['"', '}', ')']
        $numOfSurrounders = length($surrounders);
        // 3
        $indexes = keys($surrounders);
        // [0, 1, 2]
        $items = split($separator, $text);
        // ['foo', '("bar', 'baz"', 'alpha)', 'beta']
        // The initial state
        $state = (object) ['chunks' => [], 'counts' => array_fill(0, $numOfSurrounders, 0), 'total' => 0];
        // We will iterate over $items and update the $state while adding them
        // For each item we need to update counts and chunks
        // Updates count for a single surrender (the surrender at $index)
        // $item : the item we are adding
        // $counts : the previous counts
        $updateCountAt = curry(function ($item, $counts, $index) use($openings, $closings) {
            $count = occurences(__(), $item);
            return $openings[$index] == $closings[$index] ? ($counts[$index] + $count($openings[$index])) % 2 : $counts[$index] + $count($openings[$index]) - $count($closings[$index]);
        });
        // Updates counts for all surrenders
        $updateCounts = curry(function ($item, $counts) use($indexes, $updateCountAt) {
            return map($updateCountAt($item, $counts), $indexes);
        });
        // Adds an item to the state and returns a new state
        $addItem = function ($state, $item) use($separator, $updateCounts) {
            $counts = $updateCounts($item, get('counts', $state));
            $newChunks = 0 == $state->total ? append($item, $state->chunks) : append(last($state->chunks) . $separator . $item, init($state->chunks));
            return (object) ['chunks' => $newChunks, 'counts' => $counts, 'total' => sum($counts)];
        };
        // Returns the chunks of the resulting state after adding all items
        return get('chunks', reduce($addItem, $state, $items));
    };
    return apply(curry($chunks), func_get_args());
}
Exemple #16
0
/**
 * Checks if a list of attribute/value of an object/array passes any of the given predicates.
 * ```php
 * $persons = [
 *     ['name' => 'foo', 'age' => 11],
 *     ['name' => 'bar', 'age' => 9],
 *     ['name' => 'baz', 'age' => 16],
 *     ['name' => 'zeta', 'age' => 33],
 *     ['name' => 'beta', 'age' => 25]
 * ];
 * 
 * $isValid = satisfiesAny([
 *     'name' => startsWith('b'),
 *     'age' => gt(__(), 15)
 * ]);
 * 
 * filter($isValid, $persons);
 * // [
 * //   ['name' => 'bar', 'age' => 9],
 * //   ['name' => 'baz', 'age' => 16],
 * //   ['name' => 'zeta', 'age' => 33],
 * //   ['name' => 'beta', 'age' => 25]
 * // ]
 * ```
 *
 * @signature {String: (a -> Boolean)} -> {k : a} -> Boolean
 * @param  array $predicates
 * @param  mixed $object
 * @return bool
 */
function satisfiesAny()
{
    $satisfiesAny = function ($predicates, $object) {
        $predicates = map(function ($pair) {
            return satisfies($pair[1], $pair[0]);
        }, toPairs($predicates));
        $predicates = apply(_f('any'), $predicates);
        return $predicates($object);
    };
    return apply(curry($satisfiesAny), func_get_args());
}
Exemple #17
0
/**
 * Returns `$a >= $b`.
 *
 * @signature * -> * -> Boolean
 * @param  mixed $a
 * @param  mixed $b
 * @return bool
 */
function gte()
{
    return apply(curry(function ($a, $b) {
        return $a >= $b;
    }), func_get_args());
}
 public function init($param = 0)
 {
     $this->_userModel = $this->model('user');
     if (curry($_SESSION['userInformation'])) {
         $this->_userInfo = $_SESSION['userInformation'];
         $this->view('head', ['title' => $this->_userInfo->username . ' | Login - Planningsysteem']);
         $this->view('header', ['loggedInUserInfo' => $this->_userInfo, 'selected' => '', 'slideout' => true, 'username' => $this->_userInfo->username]);
         $this->view('login', ['register' => false, 'alreadyLoggedIn' => true, 'username' => $this->_userInfo->username]);
         $this->view('footer', ['loggedInUserInfo' => $this->_userInfo]);
         exit;
     } else {
         if (curry($_POST['username']) && curry($_POST['password'])) {
             if (curry($_SESSION['lastLogin'])) {
                 if (time() - $_SESSION['lastLogin'] < 2) {
                     echo json_encode(['code' => 0, 'msg' => 'Wacht alstublieft een seconde voordat u weer probeert in te loggen.']);
                     exit;
                 }
             }
             $_SESSION['lastLogin'] = time();
             if (empty($_POST['username']) || empty($_POST['password'])) {
                 echo json_encode(['code' => 0, 'message' => 'Een van de verplichte velden is leeg.']);
                 exit;
             }
             if ($this->_userModel->determinateUsername($_POST['username'])) {
                 if (!($this->_userInformation = $this->_userModel->fetchAllUserInformationByEmailAddress($_POST['username']))) {
                     echo json_encode(['code' => 0, 'msg' => 'Dat Email-adress bestaat niet.', 'showTime' => 2000]);
                     exit;
                 }
             } else {
                 if (!($this->_userInformation = $this->_userModel->fetchAllUserInformationByUsername($_POST['username']))) {
                     echo json_encode(['code' => 0, 'msg' => 'Die gebruikersnaam bestaat niet.', 'showTime' => 2000]);
                     exit;
                 }
             }
             if (password_hash($_POST['password'], PASSWORD_BCRYPT, ['salt' => $this->_userInformation->salt]) == $this->_userInformation->password) {
                 if (curry($_SESSION['lastLogin'])) {
                     unset($_SESSION['lastLogin']);
                 }
                 if (!$this->_userInformation->has_own_password) {
                     $_SESSION['tmpUserInformation'] = $this->_userInformation;
                     echo json_encode(['code' => 3]);
                     exit;
                 }
                 $_SESSION['userInformation'] = $this->_userInformation;
                 $this->_userModel->setLastLogin($this->_userInformation->werknemer_id);
                 if ($_POST['stayLoggedIn'] == 'true') {
                     $this->_cookieString = $this->_userModel->createCookieString($_SESSION['userInformation']->werknemer_id);
                     if (!$this->_cookieString) {
                         echo json_encode(['code' => 1]);
                     } else {
                         setcookie('gpl', $this->_cookieString, time() + 10 * 365 * 24 * 60 * 60, "/");
                         echo json_encode(['code' => 1]);
                     }
                 } else {
                     echo json_encode(['code' => 1]);
                 }
             } else {
                 echo json_encode(['code' => 0, 'msg' => 'Incorrect wachtwoord.', 'showTime' => 3000]);
                 exit;
             }
         } else {
             if (curry($_COOKIE['gpl'])) {
                 $this->_userInfo = $this->_userModel->getCookieInformationByString($_COOKIE['gpl']);
                 if (!$this->_userInfo) {
                     setcookie("gpl", "", time() - 1, '/');
                     header("Location: /Planningsysteem/login/");
                     exit;
                 } else {
                     $_SESSION['userInformation'] = $this->_userInfo;
                     header('Location: /Planningsysteem/' . $this->_userInfo->username . '/');
                     exit;
                 }
             } else {
                 $this->view('head', ['title' => 'Login | Planningsysteem']);
                 $this->view('header', ['loggedInUserInfo' => $this->_userInfo, 'loginText']);
                 $this->view('login');
                 $this->view('footer', ['loggedInUserInfo' => $this->_userInfo, 'loginPage']);
                 exit;
             }
         }
     }
 }
Exemple #19
0
/**
 * Converts a variable to its string value.
 * ```php
 * toString(53)); // '53'
 * toString(true)); // 'true'
 * toString(false)); // 'false'
 * toString(null)); // 'null'
 * toString('Hello World')); // '"Hello World"'
 * toString([])); // '[]'
 * toString(new \stdClass)); // '{}'
 * toString(function(){})); // '[Function]'
 * toString(Error::of('Ooops'))); // '[Error: Ooops]'
 * toString(fopen('php://temp', 'r'))); // '[Resource]'
 * toString(['hi', 'hello', 'yo'])); // '["hi", "hello", "yo"]'
 * toString([
 *     'object' => Stream::of(null),
 *     'numbers' => [1, 2, 3],
 *     'message'
 * ]); // '{object: Stream(Null), numbers: [1, 2, 3], 0: "message"]'
 * ```
 *
 * @signature * -> String
 * @param  mixed $something
 * @return string
 */
function toString()
{
    $toString = function ($something) {
        switch (type($something)) {
            case 'String':
                return "\"{$something}\"";
                break;
            case 'Boolean':
                return $something ? 'true' : 'false';
                break;
            case 'Null':
                return 'null';
                break;
            case 'Number':
                return (string) $something;
                break;
            case 'List':
                return '[' . join(', ', map(toString(), $something)) . ']';
                break;
            case 'Error':
            case 'Stream':
                return $something->__toString();
            case 'Object':
            case 'Array':
                return '{' . join(', ', map(function ($pair) {
                    return $pair[0] . ': ' . toString($pair[1]);
                }, toPairs($something))) . '}';
            default:
                return '[' . type($something) . ']';
        }
    };
    return apply(curry($toString), func_get_args());
}
Exemple #20
0
});
defun('loop', function ($f, $acc) {
    return trampoline(y(function ($y, $f, $n, $x, $_) {
        list($stop, $x) = $f($x, $n);
        return [$stop, $stop ? $x : $y($f, $n + 1, $x)];
    }, $f, 0, $acc));
});
defun('trampoline', function ($f) {
    for ($stop = false; !$stop; list($stop, $f) = $f(null)) {
    }
    return $f;
});
defun('y', function ($f) {
    $cf = curry($f);
    return curry(function ($x) use($cf) {
        return $cf(y($cf), $x);
    });
});
defun('stream_take', function ($n, $s) {
    return trampoline(y(function ($f, $x, $n, $s, $_) {
        if (!$n) {
            return [true, $x];
        }
        list($h, $t) = $s(null);
        return [false, $f(snoc($h, $x), $n - 1, $t)];
    }, [], $n, $s));
});
defun('stream_drop', function ($n, $s) {
    return trampoline(y(function ($f, $n, $s, $_) {
        if (!$n) {
            return [true, $s];
Exemple #21
0
        // Source: http://www.php.net/manual/en/functions.user-defined.php
        $valid = '/[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*/';
        array_map(function ($x) {
            if ($x[1]) {
                error($x[0]);
            }
        }, array(array("Invalid name for {$name}", !preg_match($valid, $name)), array("Cannot redeclare {$name}", function_exists($name))));
        // Declare $name globally; static $f is a poor man's lexical scope.
        eval("function {$name}() {\n                     static \$defined = true;  // Used by arity\n                     static \$f = NULL;\n                     \$args = func_get_args();\n                     return (is_null(\$f))? \$f = \$args[0]\n                                          : call_user_func_array(\$f, \$args);\n                   }");
        // Initialise $f to $expr
        return $name($curry($expr));
    };
    // Make these functions available in curried form
    $defun('defun', $defun);
    defun('op', function ($x) use($op) {
        return in_array($x, array('array', 'new')) ? $op($x) : curry($op($x));
    });
    defun('curry', $curry);
    defun('curry_', $curry_);
    defun('arity', $arity);
});
defun('key_map', function ($f, $a) {
    return array_combine(array_keys($a), array_map(op($f), array_keys($a), $a));
});
defun('defuns', key_map('defun'));
defuns(array('uncurry' => function ($f, $args) {
    return call_user_func_array(op($f), $args);
}, 'up_to' => function ($n) {
    return $n ? range(0, $n - 1) : array();
}, 'random' => function ($_) {
    return abs(mt_rand());
Exemple #22
0
/**
 * Takes a callable $f taking several arguments and converts it into a cascade
 * of functions of a single argument, e.g. given a function
 * 
 *     $f = function($x1, $x2, $x3) { ... };
 * 
 * curry($f) produces a new function $g such that:
 * 
 *     $g = function($x1) {
 *         return function($x2) {
 *             return function($x3) {
 *                 return $f($x1, $x2, $x3);
 *             };
 *         };
 *     };
 * 
 * By default, curry "curries" all the **required** arguments of a function
 * If $n is given, the "cascade of functions" is only created for that many arguments
 * This is useful for functions that are variadic or have optional arguments
 */
function curry(callable $f, $n = -1)
{
    if ($n < 0) {
        $n = n_required_args($f);
    }
    // If we have a function of 0 or 1 arguments, there is nothing to do
    if ($n < 2) {
        return $f;
    }
    // Otherwise return a new function that gathers the arguments
    // We know that $f takes at least 2 arguments
    return function ($x) use($f, $n) {
        return curry(bind($f, $x), $n - 1);
    };
}
Exemple #23
0
function find_and_load($type, $resource_path, $data, $strategy)
{
    $home_handler_path = full_home_path($type, $resource_path);
    if (!load_file($home_handler_path, $data, $strategy, curry('run_filter', '_before', $resource_path, $home_handler_path))) {
        $root_handler_path = full_root_path($type, $resource_path);
        return load_file($root_handler_path, $data, $strategy, curry('run_filter', '_before', $resource_path, $root_handler_path));
    }
    return true;
}
Exemple #24
0
<body>
    <div id="Wrapper">
        <header>
                <div class="navbar-fixed">
                    <nav class="red darken-4">
                        <div class="nav-wrapper">
                            <div class="row">
                                <div class="col s12">
                                    <?php 
//var_dump($data);
// If the slideout parameter is not set, it will be rendered
if (!curry($data['slideout']) && $data['loggedInUserInfo']) {
    ?>
                                        <a href="#" data-activates="slide-out" class="button-collapse left"><i class="mdi-navigation-menu"></i></a>
                                    <?php 
}
?>
                                        <a href="#" class="brand-name left truncate">Planningsysteem</a>
                                        <div class="navbar-options right ">
                                            <?php 
if ($data['loggedInUserInfo']) {
    ?>
                                                <div class="hide-on-small-only">
                                                    <a href="logout/"><i class="tiny mdi-action-exit-to-app"></i>Logout</a>
                                                </div>
                                                <div class="hide-on-med-and-up">
                                                    <a class="settings dropdown-button" href="#" data-activates="NavBarOptionsDropDown">
                                                        <i class="mdi-navigation-more-vert"></i>
                                                    </a>
                                                </div>
Exemple #25
0
<main>
    <div class="container">
        <div class="row">
            <div class="card-wrapper login col loading-animation loading-bottom">
                <div class="card">
                    <div class="card-content">
                       <?php 
if (curry($data['alreadyLoggedIn'])) {
    echo '<h5 class="center-align" >Hey, ' . htmlentities($data['username'], ENT_QUOTES) . '!</h5>';
    ?>

                            <div id="loginForm">
                                <div class="center-align">
                                   <p>You're already <?php 
    if ($data['register'] == true) {
        echo 'registered, and logged in.';
    } else {
        echo 'Logged in.';
    }
    ?>
</p>
                                   <button id="logOut" class="btn waves-effect waves-light red darken-4">Logout</button>
                                </div>
                            </div>
                            <?php 
} else {
    ?>
                            <h5>Inloggen</h5>
                            <div id="loginForm">
                                    <div class="row">
                                        <div class="input-field col s12">
/**
 * Returns a curried version of array_map.
 *
 * @param callable $function
 *
 * @return callable
 */
function map(callable $function)
{
    return curry('array_map', $function);
}
Exemple #27
0
 /**
  * @return callable
  */
 protected function getCurriedFunction()
 {
     return curry(function ($a, $b) {
         return $a + $b;
     });
 }
Exemple #28
0
<?php

require "../Phunctional.php";
function doubleValue($n)
{
    return $n * 2;
}
function add5($n)
{
    return $n + 5;
}
//curry: allows for functional curry techniques, (only works on functions with defined parameters).
$add_three_numbers = curry(function ($a, $b, $c) {
    return $a + $b + $c;
});
$add_ten_to_two_numbers = $add_three_numbers(10);
var_dump($add_ten_to_two_numbers(1, 2));
// int(13)
$add_15_to_one_number = $add_ten_to_two_numbers(5);
var_dump($add_15_to_one_number(27));
// int(42)
//composition: (f.g)x == f(g(x))
$not_return_value = composition("doubleValue", "add5");
var_dump($not_return_value(1));
//int(12)
var_dump($not_return_value(0));
//int(10)
//fix: passes the function into it's self as the first parameter, allows resursive annoymous functions
$fib = fix(function ($fib, $n) {
    if ($n <= 0) {
        return 0;
Exemple #29
0
function common_replace_urls_callback($text, $callback, $notice_id = null)
{
    // Start off with a regex
    $regex = '#' . '(?:^|[\\s\\<\\>\\(\\)\\[\\]\\{\\}\\\'\\\\";]+)(?![\\@\\!\\#])' . '(' . '(?:' . '(?:' . '(?:' . '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)' . '|' . '(?:(?:mailto|aim|tel|xmpp):)' . ')' . '(?:[\\pN\\pL\\-\\_\\+\\%\\~]+(?::[\\pN\\pL\\-\\_\\+\\%\\~]+)?\\@)?' . '(?:' . '(?:' . '\\[[\\pN\\pL\\-\\_\\:\\.]+(?<![\\.\\:])\\]' . ')|(?:' . '[\\pN\\pL\\-\\_\\:\\.]+(?<![\\.\\:])' . ')' . ')' . ')' . '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' . '|(?:' . '\\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(?:\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})|(?::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5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZW|local|loc|onion)' . ')(?![\\pN\\pL\\-\\_])' . ')' . '(?:' . '(?:\\:\\d+)?' . '(?:/[\\pN\\pL$\\,\\!\\(\\)\\.\\:\\-\\_\\+\\/\\=\\&\\;\\%\\~\\*\\$\\+\'@]*)?' . '(?:\\?[\\pN\\pL\\$\\,\\!\\(\\)\\.\\:\\-\\_\\+\\/\\=\\&\\;\\%\\~\\*\\$\\+\'@\\/]*)?' . '(?:\\#[\\pN\\pL$\\,\\!\\(\\)\\.\\:\\-\\_\\+\\/\\=\\&\\;\\%\\~\\*\\$\\+\'\\@/\\?\\#]*)?' . ')(?<![\\?\\.\\,\\#\\,])' . ')' . '#ixu';
    //preg_match_all($regex,$text,$matches);
    //print_r($matches);
    return preg_replace_callback($regex, curry('callback_helper', $callback, $notice_id), $text);
}
Exemple #30
0
echo $increment($increment($increment(3)));
function map($fn, $a)
{
    $newA = array();
    foreach ($a as $key => $val) {
        $newA[] = $fn($val, $key);
    }
    return $newA;
}
$love = array('I' => 'me', 'Love' => 'miss', 'You' => 'aar');
$tell = function ($val, $key) {
    echo $key, ' => ', $val, "\n";
};
map($tell, $love);
$increment = curry('map', function ($val, $key) use($tell) {
    $val .= ' more';
    $tell($val, $key);
});
$increment($love);
// ***************************
//  NEW CURRY (For me)
// ***************************
function newCurry($fn, $data)
{
    return function ($argv) use($data, $fn) {
        return $fn();
    };
}
/** demo 1: */
$match = newCurry(function ($match, $data) {
    preg_match($match, $data, $results);
    return $results;