コード例 #1
0
ファイル: SessionActionsTest.php プロジェクト: rayku/rayku
 /**
  * @test
  * @group mocking
  */
 public function shouldReturnAJsonRepresentationOfASession()
 {
     $session = mock('WhiteboardSession');
     when($session)->info()->thenReturn(array('pretend-that' => 'this is a valid session info'));
     when($this->request)->getParameter('token')->thenReturn('aTokenValue');
     when($this->whiteboardSessionPeer)->loadByToken('aTokenValue')->thenReturn($session);
     $this->actions->executeInfo($this->request);
     $json = $this->getResponseContents();
     $this->assertEquals('{"pretend-that":"this is a valid session info"}', $json);
 }
コード例 #2
0
 function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $this->redirection->setRequest($request);
     $base = $this->settings->urlPrefix();
     $base = $base ? "{$base}..." : '*';
     return $this->router->set([$base => [when($this->settings->requireAuthentication(), AuthenticationMiddleware::class), '.' => page('platform/home.html'), 'settings...' => [when($this->settings->enableUsersManagement(), ['users-management...' => ['users' => factory(function (UsersPage $page) {
         // This is done here just to show off this possibility
         $page->templateUrl = 'platform/users/users.html';
         return $page;
     }), 'users/@id' => UserPage::class, 'profile' => factory(function (UserPage $page) {
         $page->editingSelf = true;
         return $page;
     })]])]]])->__invoke($request, $response, $next);
 }
コード例 #3
0
ファイル: ListaHelper.php プロジェクト: DaniloEpic/slast
 public static function loop_when()
 {
     $j = self::$lista->from();
     $k = 0;
     do {
         if ($j < self::$lista->getSize()) {
             when(self::$lista, $j);
             $j = $j + 1;
             $k = $k + 1;
         } else {
             $k = self::$lista->getQuantidadePorPagina();
         }
     } while ($k < self::$lista->getQuantidadePorPagina());
 }
コード例 #4
0
ファイル: model.Comment.php プロジェクト: homebru/bandb
 /**
  * Function: create
  * Attempts to create a comment using the passed information. If a Defensio API key is present, it will check it.
  *
  * Parameters:
  *     $author - The name of the commenter.
  *     $email - The commenter's email.
  *     $url - The commenter's website.
  *     $body - The comment.
  *     $post - The <Post> they're commenting on.
  *     $type - The type of comment. Optional, used for trackbacks/pingbacks.
  */
 static function create($author, $email, $url, $body, $post, $type = null)
 {
     if (!self::user_can($post->id) and !in_array($type, array("trackback", "pingback"))) {
         return;
     }
     $config = Config::current();
     $route = Route::current();
     $visitor = Visitor::current();
     if (!$type) {
         $status = $post->user_id == $visitor->id ? "approved" : $config->default_comment_status;
         $type = "comment";
     } else {
         $status = $type;
     }
     if (!empty($config->defensio_api_key)) {
         $comment = array("user-ip" => $_SERVER['REMOTE_ADDR'], "article-date" => when("Y/m/d", $post->created_at), "comment-author" => $author, "comment-type" => $type, "comment-content" => $body, "comment-author-email" => $email, "comment-author-url" => $url, "permalink" => $post->url(), "referrer" => $_SERVER['HTTP_REFERER'], "user-logged-in" => logged_in());
         $defensio = new Defensio($config->url, $config->defensio_api_key);
         list($spam, $spaminess, $signature) = $defensio->auditComment($comment);
         if ($spam) {
             self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], "spam", $signature, null, null, $post, $visitor->id);
             error(__("Spam Comment"), __("Your comment has been marked as spam. It will have to be approved before it will show up.", "comments"));
         } else {
             $comment = self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $status, $signature, null, null, $post, $visitor->id);
             fallback($_SESSION['comments'], array());
             $_SESSION['comments'][] = $comment->id;
             if (isset($_POST['ajax'])) {
                 exit("{ comment_id: " . $comment->id . ", comment_timestamp: \"" . $comment->created_at . "\" }");
             }
             Flash::notice(__("Comment added."), $post->url() . "#comment_" . $comment->id);
         }
     } else {
         $comment = self::add($body, $author, $url, $email, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $status, "", null, null, $post, $visitor->id);
         fallback($_SESSION['comments'], array());
         $_SESSION['comments'][] = $comment->id;
         if (isset($_POST['ajax'])) {
             exit("{ comment_id: " . $comment->id . ", comment_timestamp: \"" . $comment->created_at . "\" }");
         }
         Flash::notice(__("Comment added."), $post->url() . "#comment_" . $comment->id);
     }
 }
コード例 #5
0
ファイル: Paginator.php プロジェクト: betsyzhang/chyrp
 /**
  * Function: __construct
  * Prepares an array for pagination.
  *
  * Parameters:
  *     $array - The array to paginate.
  *     $per_page - Number of items per page.
  *     $name - The name of the $_GET parameter to use for determining the current page.
  *     $model - If this is true, each item in $array that gets shown on the page will be
  *              initialized as a model of whatever is passed as the second argument to $array.
  *              The first argument of $array is expected to be an array of IDs.
  *     $page - Page number to start at.
  *
  * Returns:
  *     A paginated array of length $per_page or smaller.
  */
 public function __construct($array, $per_page = 5, $name = "page", $model = null, $page = null)
 {
     self::$names[] = $name;
     $this->array = (array) $array;
     $this->per_page = $per_page;
     $this->name = $name;
     $this->model = fallback($model, count($this->array) == 2 and is_array($this->array[0]) and is_string($this->array[1]) and class_exists($this->array[1]));
     if ($model) {
         list($this->array, $model_name) = $this->array;
     }
     $this->total = count($this->array);
     $this->page = oneof($page, @$_GET[$name], 1);
     $this->pages = ceil($this->total / $this->per_page);
     $offset = ($this->page - 1) * $this->per_page;
     $this->result = array();
     if ($model) {
         for ($i = $offset; $i < $offset + $this->per_page; $i++) {
             if (isset($this->array[$i])) {
                 $this->result[] = new $model_name(null, array("read_from" => $this->array[$i]));
             }
         }
     } else {
         $this->result = array_slice($this->array, $offset, $this->per_page);
     }
     $shown_dates = array();
     if ($model) {
         foreach ($this->result as &$result) {
             if (isset($result->created_at)) {
                 $pinned = (isset($result->pinned) and $result->pinned);
                 $shown = in_array(when("m-d-Y", $result->created_at), $shown_dates);
                 $result->first_of_day = (!$pinned and !$shown and !AJAX);
                 if (!$pinned and !$shown) {
                     $shown_dates[] = when("m-d-Y", $result->created_at);
                 }
             }
         }
     }
     $this->paginated = $this->paginate = $this->list =& $this->result;
 }
コード例 #6
0
ファイル: runtime.php プロジェクト: betsyzhang/chyrp
function twig_strftime_format_filter($timestamp, $format = '%x %X')
{
    return when($format, $timestamp, true);
}
コード例 #7
0
<?php

/**
 * Somewhere within your application:
 * 
 * This is just an example of what you can do.
 */
namespace FileSystem;

class Space extends Directory
{
}
$application->bind('FileSystem\\Space', function (User $user) {
    return new Space($user->allocatedSpacePath);
});
// In your business logic:
use FileSystem\File;
use FileSystem\FileSystem;
use FileSystem\Space;
when('i want to make a directory inside my space', then(apply(a(function (FileSystem $fileSystem, Space $space, File $file) {
    $fileSystem->write($file, inside($space));
}))));
コード例 #8
0
<?php

use FileSystem\File;
use FileSystem\FileSystem;
when('i want to rename a file', then(apply(a(function (FileSystem $fileSystem, File $file) {
    $fileSystem->rename($file);
}))));
/*
|--------------------------------------------------------------------------
| Notes: renaming behind the scenes.
|--------------------------------------------------------------------------
|
| Behind the scenes in your technical code you call:
| $file->renameTo ( 'new name' );
|
| The business code here can choose to save it to the file
| system as it has done in the above code. Other options
| might include just ignoring the technical provided name
| and renaming the file to something else.
*/
コード例 #9
0
ファイル: edit_form.php プロジェクト: vito/chyrp-site
                <option value="spam"<?php 
selected($comment->status, "spam");
?>
><?php 
echo __("Spam", "comments");
?>
</option>
            </select>
        </p>
        <p>
            <label for="created_at"><?php 
echo __("Timestamp");
?>
</label>
            <input class="text" type="text" name="created_at" value="<?php 
echo when("F jS, Y H:i:s", $comment->created_at);
?>
" id="created_at" />
        </p>
        <div class="clear"></div>
    </div>
    <br />
    <input type="hidden" name="id" value="<?php 
echo fix($comment->id);
?>
" id="id" />
    <input type="hidden" name="ajax" value="true" id="ajax" />
    <div class="buttons">
        <input type="submit" value="<?php 
echo __("Update");
?>
コード例 #10
0
ファイル: Admin.php プロジェクト: eadz/chyrp
 /**
  * Function: export
  * Export posts, pages, etc.
  */
 public function export()
 {
     if (!Visitor::current()->group->can("add_post")) {
         show_403(__("Access Denied"), __("You do not have sufficient privileges to export content."));
     }
     if (empty($_POST)) {
         return $this->display("export");
     }
     $config = Config::current();
     $trigger = Trigger::current();
     $route = Route::current();
     $exports = array();
     if (isset($_POST['posts'])) {
         list($where, $params) = keywords($_POST['filter_posts'], "post_attributes.value LIKE :query OR url LIKE :query", "post_attributes");
         if (!empty($_GET['month'])) {
             $where["created_at like"] = $_GET['month'] . "-%";
         }
         $visitor = Visitor::current();
         if (!$visitor->group->can("view_draft", "edit_draft", "edit_post", "delete_draft", "delete_post")) {
             $where["user_id"] = $visitor->id;
         }
         $results = Post::find(array("placeholders" => true, "drafts" => true, "where" => $where, "params" => $params));
         $ids = array();
         foreach ($results[0] as $result) {
             $ids[] = $result["id"];
         }
         if (!empty($ids)) {
             $posts = Post::find(array("drafts" => true, "where" => array("id" => $ids), "order" => "id ASC"), array("filter" => false));
         } else {
             $posts = new Paginator(array());
         }
         $latest_timestamp = 0;
         foreach ($posts as $post) {
             if (strtotime($post->created_at) > $latest_timestamp) {
                 $latest_timestamp = strtotime($post->created_at);
             }
         }
         $id = substr(strstr($config->url, "//"), 2);
         $id = str_replace("#", "/", $id);
         $id = preg_replace("/(" . preg_quote(parse_url($config->url, PHP_URL_HOST)) . ")/", "\\1," . date("Y", $latest_timestamp) . ":", $id, 1);
         $posts_atom = '<?xml version="1.0" encoding="utf-8"?>' . "\r";
         $posts_atom .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:chyrp="http://chyrp.net/export/1.0/">' . "\r";
         $posts_atom .= '    <title>' . fix($config->name) . ' Posts</title>' . "\r";
         $posts_atom .= '    <subtitle>' . fix($config->description) . '</subtitle>' . "\r";
         $posts_atom .= '    <id>tag:' . parse_url($config->url, PHP_URL_HOST) . ',' . date("Y", $latest_timestamp) . ':Chyrp</id>' . "\r";
         $posts_atom .= '    <updated>' . date("c", $latest_timestamp) . '</updated>' . "\r";
         $posts_atom .= '    <link href="' . $config->url . '" rel="self" type="application/atom+xml" />' . "\r";
         $posts_atom .= '    <generator uri="http://chyrp.net/" version="' . CHYRP_VERSION . '">Chyrp</generator>' . "\r";
         foreach ($posts as $post) {
             $title = fix($post->title(), false);
             fallback($title, ucfirst($post->feather) . " Post #" . $post->id);
             $updated = $post->updated ? $post->updated_at : $post->created_at;
             $tagged = substr(strstr(url("id/" . $post->id), "//"), 2);
             $tagged = str_replace("#", "/", $tagged);
             $tagged = preg_replace("/(" . preg_quote(parse_url($post->url(), PHP_URL_HOST)) . ")/", "\\1," . when("Y-m-d", $updated) . ":", $tagged, 1);
             $url = $post->url();
             $posts_atom .= '    <entry xml:base="' . fix($url) . '">' . "\r";
             $posts_atom .= '        <title type="html">' . $title . '</title>' . "\r";
             $posts_atom .= '        <id>tag:' . $tagged . '</id>' . "\r";
             $posts_atom .= '        <updated>' . when("c", $updated) . '</updated>' . "\r";
             $posts_atom .= '        <published>' . when("c", $post->created_at) . '</published>' . "\r";
             $posts_atom .= '        <link href="' . fix($trigger->filter($url, "post_export_url", $post)) . '" />' . "\r";
             $posts_atom .= '        <author chyrp:user_id="' . $post->user_id . '">' . "\r";
             $posts_atom .= '            <name>' . fix(oneof($post->user->full_name, $post->user->login)) . '</name>' . "\r";
             if (!empty($post->user->website)) {
                 $posts_atom .= '            <uri>' . fix($post->user->website) . '</uri>' . "\r";
             }
             $posts_atom .= '            <chyrp:login>' . fix($post->user->login) . '</chyrp:login>' . "\r";
             $posts_atom .= '        </author>' . "\r";
             $posts_atom .= '        <content>' . "\r";
             foreach ($post->attributes as $key => $val) {
                 $posts_atom .= '            <' . $key . '>' . fix($val) . '</' . $key . '>' . "\r";
             }
             $posts_atom .= '        </content>' . "\r";
             foreach (array("feather", "clean", "url", "pinned", "status") as $attr) {
                 $posts_atom .= '        <chyrp:' . $attr . '>' . fix($post->{$attr}) . '</chyrp:' . $attr . '>' . "\r";
             }
             $trigger->filter($posts_atom, "posts_export", $post);
             $posts_atom .= '    </entry>' . "\r";
         }
         $posts_atom .= '</feed>' . "\r";
         $exports["posts.atom"] = $posts_atom;
     }
     if (isset($_POST['pages'])) {
         list($where, $params) = keywords($_POST['filter_pages'], "title LIKE :query OR body LIKE :query", "pages");
         $pages = Page::find(array("where" => $where, "params" => $params, "order" => "id ASC"), array("filter" => false));
         $latest_timestamp = 0;
         foreach ($pages as $page) {
             if (strtotime($page->created_at) > $latest_timestamp) {
                 $latest_timestamp = strtotime($page->created_at);
             }
         }
         $pages_atom = '<?xml version="1.0" encoding="utf-8"?>' . "\r";
         $pages_atom .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:chyrp="http://chyrp.net/export/1.0/">' . "\r";
         $pages_atom .= '    <title>' . fix($config->name) . ' Pages</title>' . "\r";
         $pages_atom .= '    <subtitle>' . fix($config->description) . '</subtitle>' . "\r";
         $pages_atom .= '    <id>tag:' . parse_url($config->url, PHP_URL_HOST) . ',' . date("Y", $latest_timestamp) . ':Chyrp</id>' . "\r";
         $pages_atom .= '    <updated>' . date("c", $latest_timestamp) . '</updated>' . "\r";
         $pages_atom .= '    <link href="' . $config->url . '" rel="self" type="application/atom+xml" />' . "\r";
         $pages_atom .= '    <generator uri="http://chyrp.net/" version="' . CHYRP_VERSION . '">Chyrp</generator>' . "\r";
         foreach ($pages as $page) {
             $updated = $page->updated ? $page->updated_at : $page->created_at;
             $tagged = substr(strstr($page->url(), "//"), 2);
             $tagged = str_replace("#", "/", $tagged);
             $tagged = preg_replace("/(" . preg_quote(parse_url($page->url(), PHP_URL_HOST)) . ")/", "\\1," . when("Y-m-d", $updated) . ":", $tagged, 1);
             $url = $page->url();
             $pages_atom .= '    <entry xml:base="' . fix($url) . '" chyrp:parent_id="' . $page->parent_id . '">' . "\r";
             $pages_atom .= '        <title type="html">' . fix($page->title) . '</title>' . "\r";
             $pages_atom .= '        <id>tag:' . $tagged . '</id>' . "\r";
             $pages_atom .= '        <updated>' . when("c", $updated) . '</updated>' . "\r";
             $pages_atom .= '        <published>' . when("c", $page->created_at) . '</published>' . "\r";
             $pages_atom .= '        <link href="' . fix($trigger->filter($url, "page_export_url", $page)) . '" />' . "\r";
             $pages_atom .= '        <author chyrp:user_id="' . fix($page->user_id) . '">' . "\r";
             $pages_atom .= '            <name>' . fix(oneof($page->user->full_name, $page->user->login)) . '</name>' . "\r";
             if (!empty($page->user->website)) {
                 $pages_atom .= '            <uri>' . fix($page->user->website) . '</uri>' . "\r";
             }
             $pages_atom .= '            <chyrp:login>' . fix($page->user->login) . '</chyrp:login>' . "\r";
             $pages_atom .= '        </author>' . "\r";
             $pages_atom .= '        <content type="html">' . fix($page->body) . '</content>' . "\r";
             foreach (array("show_in_list", "list_order", "clean", "url") as $attr) {
                 $pages_atom .= '        <chyrp:' . $attr . '>' . fix($page->{$attr}) . '</chyrp:' . $attr . '>' . "\r";
             }
             $trigger->filter($pages_atom, "pages_export", $page);
             $pages_atom .= '    </entry>' . "\r";
         }
         $pages_atom .= '</feed>' . "\r";
         $exports["pages.atom"] = $pages_atom;
     }
     if (isset($_POST['groups'])) {
         list($where, $params) = keywords($_POST['filter_groups'], "name LIKE :query", "groups");
         $groups = Group::find(array("where" => $where, "params" => $params, "order" => "id ASC"));
         $groups_yaml = array("groups" => array(), "permissions" => array());
         foreach (SQL::current()->select("permissions", "*", array("group_id" => 0))->fetchAll() as $permission) {
             $groups_yaml["permissions"][$permission["id"]] = $permission["name"];
         }
         foreach ($groups as $index => $group) {
             $groups_yaml["groups"][$group->name] = $group->permissions;
         }
         $exports["groups.yaml"] = YAML::dump($groups_yaml);
     }
     if (isset($_POST['users'])) {
         list($where, $params) = keywords($_POST['filter_users'], "login LIKE :query OR full_name LIKE :query OR email LIKE :query OR website LIKE :query", "users");
         $users = User::find(array("where" => $where, "params" => $params, "order" => "id ASC"));
         $users_yaml = array();
         foreach ($users as $user) {
             $users_yaml[$user->login] = array();
             foreach ($user as $name => $attr) {
                 if (!in_array($name, array("no_results", "group_id", "group", "id", "login", "belongs_to", "has_many", "has_one", "queryString"))) {
                     $users_yaml[$user->login][$name] = $attr;
                 } elseif ($name == "group_id") {
                     $users_yaml[$user->login]["group"] = $user->group->name;
                 }
             }
         }
         $exports["users.yaml"] = YAML::dump($users_yaml);
     }
     $trigger->filter($exports, "export");
     require INCLUDES_DIR . "/lib/zip.php";
     $zip = new ZipFile();
     foreach ($exports as $filename => $content) {
         $zip->addFile($content, $filename);
     }
     $zip_contents = $zip->file();
     $filename = sanitize(camelize($config->name), false, true) . "_Export_" . date("Y-m-d");
     header("Content-type: application/octet-stream");
     header("Content-Disposition: attachment; filename=\"" . $filename . ".zip\"");
     header("Content-length: " . strlen($zip_contents) . "\n\n");
     echo $zip_contents;
 }
コード例 #11
0
 private function renderMenuItem(\Iterator $links, $xi, $parentIsActive, $depth = 1)
 {
     $links->rewind();
     if (!$links->valid() || $depth >= $this->props->depth) {
         return null;
     }
     return h('ul.nav.collapse.' . $this->depthClass[$depth], map($links, function (NavigationLinkInterface $link) use($xi, $depth, $parentIsActive) {
         if (!$link->isActuallyVisible() || $link->isGroup() && $link->title() == '-' && $this->props->excludeDividers) {
             return null;
         }
         $children = $link->getMenu();
         $sub = '';
         /** @var NavigationLinkInterface $child */
         foreach ($children as $child) {
             if ($child->isActuallyVisible()) {
                 $sub = '.sub';
                 break;
             }
         }
         $children->rewind();
         $active = $link->isActive() ? '.active' : '';
         $current = $link->isSelected() ? '.current' : '';
         $disabled = !$link->isActuallyEnabled();
         $url = $disabled || $link->isGroup() && !isset($link->defaultURI) ? null : $link->url();
         $disabledClass = $disabled ? '.disabled' : '';
         return [h("li{$active}{$sub}{$current}", [h("a{$active}{$disabledClass}", ['href' => $url], [when($link->icon(), h('i', ['class' => $link->icon()])), $link->title(), when(isset($xi) && $sub, h("span.{$xi}"))]), when($sub, $this->renderMenuItem($children, $xi, false, $depth + 1))])];
     }));
 }
コード例 #12
0
ファイル: comments.php プロジェクト: relisher/chyrp
 public function posts_export($atom, $post)
 {
     $comments = Comment::find(array("where" => array("post_id" => $post->id)), array("filter" => false));
     foreach ($comments as $comment) {
         $updated = $comment->updated ? $comment->updated_at : $comment->created_at;
         $atom .= "       <chyrp:comment>\r";
         $atom .= '           <updated>' . when("c", $updated) . '</updated>' . "\r";
         $atom .= '           <published>' . when("c", $comment->created_at) . '</published>' . "\r";
         $atom .= '           <author chyrp:user_id="' . $comment->user_id . '">' . "\r";
         $atom .= "               <name>" . fix($comment->author) . "</name>\r";
         if (!empty($comment->author_url)) {
             $atom .= "               <uri>" . fix($comment->author_url) . "</uri>\r";
         }
         $atom .= "               <email>" . fix($comment->author_email) . "</email>\r";
         $atom .= "               <chyrp:login>" . fix(@$comment->user->login) . "</chyrp:login>\r";
         $atom .= "               <chyrp:ip>" . long2ip($comment->author_ip) . "</chyrp:ip>\r";
         $atom .= "               <chyrp:agent>" . fix($comment->author_agent) . "</chyrp:agent>\r";
         $atom .= "           </author>\r";
         $atom .= "           <content>" . fix($comment->body) . "</content>\r";
         foreach (array("status", "signature") as $attr) {
             $atom .= "           <chyrp:" . $attr . ">" . fix($comment->{$attr}) . "</chyrp:" . $attr . ">\r";
         }
         $atom .= "       </chyrp:comment>\r";
     }
     return $atom;
 }
コード例 #13
0
ファイル: test_stack.php プロジェクト: digitalsadhu/given-php
<?php

require 'Stack.php';
describe('Stack', function () {
    Given('stack', function ($initial_contents) {
        return new Stack($initial_contents);
    });
    context('with no items', function () {
        given('initial_contents', function () {
            return [];
        });
        when(function (Stack $stack) {
            $stack->push(3);
        });
        then(function (Stack $stack) {
            return $stack->size() === 1;
        });
    });
    context('with one item', function () {
        given('initial_contents', function () {
            return ['an item'];
        });
        when(function (Stack $stack) {
            $stack->push('another item');
        });
        then(function (Stack $stack) {
            return $stack->size() === 2;
        });
    });
});
コード例 #14
0
        });
    });
    describe('calling #reportEnd', function () {
        given('errors', array());
        given('labels', array());
        given('results', array());
        given('an instance of the tap reporter', 'reporter', new TapReporter());
        context('no tests were executed', function () {
            given('total', 0);
            when('reporter #reportEnd is called', 'result', function ($reporter, $total, $errors, $labels, $results) {
                ob_start();
                $reporter->reportEnd($total, $errors, $labels, $results);
                return ob_get_clean();
            });
            then('result should be a valid string', function ($result) {
                return empty($result);
            });
        });
        context('11 tests with no errors was executed', function () {
            given('total', 11);
            when('reporter #reportEnd is called', 'result', function ($reporter, $total, $errors, $labels, $results) {
                ob_start();
                $reporter->reportEnd($total, $errors, $labels, $results);
                return ob_get_clean();
            });
            then('result should be a valid string', function ($result) {
                return !(false === strpos($result, '1..11'));
            });
        });
    });
});
コード例 #15
0
ファイル: GlobalsTest.php プロジェクト: crashuxx/phockito
 function testCanStub()
 {
     $mock = mock(MockMe::class);
     when($mock->Foo())->return(1);
     $this->assertEquals($mock->Foo(), 1);
 }
コード例 #16
0
ファイル: Model.php プロジェクト: homebru/bandb
 /**
  * Function: search
  * Returns an array of model objects that are found by the $options array.
  *
  * Parameters:
  *     $options - An array of options, mostly SQL things.
  *     $options_for_object - An array of options for the instantiation of the model.
  *
  * Options:
  *     select - What to grab from the table. @(modelname)s@ by default.
  *     from - Which table(s) to grab from? @(modelname)s.*@ by default.
  *     left_join - A @LEFT JOIN@ associative array. Example: @array("table" => "foo", "where" => "foo = :bar")@
  *     where - A string or array of conditions. @array("__(modelname)s.id = :id")@ by default.
  *     params - An array of parameters to pass to PDO. @array(":id" => $id)@ by default.
  *     group - A string or array of "GROUP BY" conditions.
  *     order - What to order the SQL result by. @__(modelname)s.id DESC@ by default.
  *     offset - Offset for SQL query.
  *     limit - Limit for SQL query.
  *
  * See Also:
  *     <Model.grab>
  */
 protected static function search($model, $options = array(), $options_for_object = array())
 {
     $model_name = strtolower($model);
     fallback($options["select"], "*");
     fallback($options["from"], pluralize(strtolower($model)));
     fallback($options["left_join"], array());
     fallback($options["where"], null);
     fallback($options["params"], array());
     fallback($options["group"], array());
     fallback($options["order"], "id DESC");
     fallback($options["offset"], null);
     fallback($options["limit"], null);
     fallback($options["placeholders"], false);
     fallback($options["ignore_dupes"], array());
     $options["where"] = (array) $options["where"];
     $options["from"] = (array) $options["from"];
     $options["select"] = (array) $options["select"];
     $trigger = Trigger::current();
     $trigger->filter($options, pluralize(strtolower($model_name)) . "_get");
     $grab = SQL::current()->select($options["from"], $options["select"], $options["where"], $options["order"], $options["params"], $options["limit"], $options["offset"], $options["group"], $options["left_join"])->fetchAll();
     $shown_dates = array();
     $results = array();
     $rows = array();
     foreach ($grab as $row) {
         foreach ($row as $column => $val) {
             $rows[$row["id"]][$column][] = $val;
         }
     }
     foreach ($rows as &$row) {
         foreach ($row as $name => &$column) {
             $column = !in_array($name, $options["ignore_dupes"]) ? array_unique($column) : $column;
             $column = count($column) == 1 ? $column[0] : $column;
         }
     }
     foreach ($rows as $result) {
         if ($options["placeholders"]) {
             $results[] = $result;
             continue;
         }
         $options_for_object["read_from"] = $result;
         $result = new $model(null, $options_for_object);
         if (isset($result->created_at)) {
             $pinned = (isset($result->pinned) and $result->pinned);
             $shown = in_array(when("m-d-Y", $result->created_at), $shown_dates);
             $result->first_of_day = (!$pinned and !$shown and !AJAX);
             if (!$pinned and !$shown) {
                 $shown_dates[] = when("m-d-Y", $result->created_at);
             }
         }
         $results[] = $result;
     }
     return $options["placeholders"] ? array($results, $model_name) : $results;
 }
コード例 #17
0
ファイル: mail_out.php プロジェクト: TabLand/dine_me
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
	<head>
		<link href='http://fonts.googleapis.com/css?family=Josefin+Sans' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" type="text/css" href="dine.css?v=0.1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
	<body id="plate">
        <div id="text">
            <?php 
$who = name();
$where = place();
$when = when();
$duration = duration();
$email = email();
$why = reason();
$mail_text = "Who:   {$who}\r\n" . "Where: {$where}\r\n" . "When:  {$when}\r\n" . "Duration: {$duration} hour(s) \r\n" . "Email: {$email}\r\n" . "Reason: {$why}\r\n";
if (verify_captcha()) {
    send_mail($mail_text, $email, $who);
    echo "Mail sent, now you must wait for me to respond.";
} else {
    echo "Captcha failed, I don't dine with robots";
}
?>
        </div>
    </body>
</html>
コード例 #18
0
 protected function render()
 {
     $prop = $this->props;
     $align = $prop->align;
     switch ($align) {
         case 'left':
             $this->attr('style', 'float:left');
             break;
         case 'right':
             $this->attr('style', 'float:right');
             break;
         case 'center':
             $this->attr('style', 'margin: 0 auto;display:block');
             break;
     }
     if (exists($prop->alt)) {
         $this->attr('alt', $prop->alt);
     }
     if (exists($prop->onClick)) {
         $this->attr('onclick', $prop->onClick);
     }
     if (exists($prop->href)) {
         $this->attr('onclick', "location='{$prop->href}'");
     }
     if (exists($prop->value)) {
         $url = $this->contentRepo->getImageUrl($prop->value, ['w' => when(isset($prop->width), $prop->width), 'h' => when(isset($prop->height), $prop->height), 'q' => when(isset($prop->quality), $prop->quality), 'fit' => when(isset($prop->fit), $prop->fit), 'fm' => when(isset($prop->format), $prop->format), 'nc' => when(!$prop->cache, '1'), 'bg' => when(isset($prop->background), $prop->background)]);
         if ($this->containerTag == 'img') {
             $this->addAttrs(['src' => $url, 'width' => $prop->width, 'height' => $prop->height]);
         } else {
             $this->attr('style', enum(';', "background-image:url({$url})", "background-repeat:no-repeat", when(exists($prop->size) && $prop->size != 'auto', "background-size:{$prop->size}"), when($prop->position, "background-position:{$prop->position}"), when($prop->width, "width:{$prop->width}px"), when($prop->height, "height:{$prop->height}px")));
         }
     }
 }
コード例 #19
0
ファイル: Post.php プロジェクト: relisher/chyrp
 /**
  * Function: url
  * Returns a post's URL.
  */
 public function url()
 {
     if ($this->no_results) {
         return false;
     }
     $config = Config::current();
     $visitor = Visitor::current();
     if (!$config->clean_urls) {
         return $config->url . "/?action=view&amp;url=" . urlencode($this->url);
     }
     $login = strpos($config->post_url, "(author)") !== false ? $this->user->login : null;
     $vals = array(when("Y", $this->created_at), when("m", $this->created_at), when("d", $this->created_at), when("H", $this->created_at), when("i", $this->created_at), when("s", $this->created_at), $this->id, urlencode($login), urlencode($this->clean), urlencode($this->url), urlencode($this->feather), urlencode(pluralize($this->feather)));
     Trigger::current()->filter($vals, "url_vals", $this);
     return $config->url . "/" . str_replace(array_keys(self::$url_attrs), $vals, $config->post_url);
 }
コード例 #20
0
ファイル: Theme.php プロジェクト: eadz/chyrp
 /**
  * Function: archive_list
  * Generates an array of all of the archives, by month.
  *
  * Parameters:
  *     $limit - Amount of months to list
  *     $order_by - What to sort it by
  *     $order - "asc" or "desc"
  *
  * Returns:
  *     The array. Each entry as "month", "year", and "url" values, stored as an array.
  */
 public function archives_list($limit = 0, $order_by = "created_at", $order = "desc")
 {
     if (isset($this->archives_list["{$limit},{$order_by},{$order}"])) {
         return $this->archives_list["{$limit},{$order_by},{$order}"];
     }
     $sql = SQL::current();
     $dates = $sql->select("posts", array("DISTINCT YEAR(created_at) AS year", "MONTH(created_at) AS month", "created_at AS created_at", "COUNT(id) AS posts"), array("status" => "public", Post::feathers()), $order_by . " " . strtoupper($order), array(), $limit == 0 ? null : $limit, null, array("created_at"));
     $archives = array();
     $grouped = array();
     while ($date = $dates->fetchObject()) {
         if (isset($grouped[$date->month . " " . $date->year])) {
             $archives[$grouped[$date->month . " " . $date->year]]["count"]++;
         } else {
             $grouped[$date->month . " " . $date->year] = count($archives);
             $archives[] = array("month" => $date->month, "year" => $date->year, "when" => $date->created_at, "url" => url("archive/" . when("Y/m/", $date->created_at)), "count" => $date->posts);
         }
     }
     return $this->archives_list["{$limit},{$order_by},{$order}"] = $archives;
 }
コード例 #21
0
        then(function ($callback) {
            return $callback() === 'foo';
        });
    });
    context('using a real context', function () {
        given('given_php', m::mock()->shouldReceive('get_value')->andReturn('foo')->getMock());
        given('callback', new EnhancedCallback(function ($foo_var) {
            return $foo_var;
        }));
        then(function ($callback, $given_php) {
            $result = $callback($given_php) === 'foo';
            m::close();
            return $result;
        });
    });
    context('parameters', function () {
        given('given_php', m::mock()->shouldReceive('get_value')->twice()->andReturn(1)->getMock());
        given('callback', new EnhancedCallback(function ($param_1, $param_2) {
            return $param_1 + $param_2;
        }));
        when('parameters', function ($given_php, EnhancedCallback $callback) {
            return $callback->parameters($given_php);
        });
        then(function ($parameters) {
            return count($parameters) === 4;
        });
        then(function ($parameters) {
            return isset($parameters[0], $parameters[1], $parameters['param_1'], $parameters['param_2']);
        });
    });
});
コード例 #22
0
ファイル: SQL.php プロジェクト: betsyzhang/chyrp
 /**
  * Function: second_from_datetime
  * Returns the second of a datetime.
  *
  * Parameters:
  *     $datetime - DATETIME value.
  */
 public function second_from_datetime($datetime)
 {
     return when("s", $datetime);
 }
コード例 #23
0
ファイル: confirm.php プロジェクト: TabLand/dine_me
} else {
    $a_valid_email = "invalid";
    $may_or_may_not = "may not";
}
echo "So your name is {$who}.<br>" . "You want to meet at {$where} on {$when} hours for {$duration} {$hours} because {$why}.<br>" . "I think I {$am_free_or_busy}<br>" . "You can be contacted at {$email},<br>" . "which to me looks to be {$a_valid_email} therefore I {$may_or_may_not} try to respond.";
?>
                <input type="hidden" name="email" value="<?php 
echo email();
?>
"/>
                <input type="hidden" name="duration" value="<?php 
echo duration();
?>
"/>
                <input type="hidden" name="when" value="<?php 
echo when();
?>
"/>
                <input type="hidden" name="why" value="<?php 
echo reason();
?>
"/>
                <input type="hidden" name="who" value="<?php 
echo name();
?>
"/>
                <input type="hidden" name="where" value="<?php 
echo place();
?>
"/>
                <input type="hidden" name="email" value="<?php 
コード例 #24
0
ファイル: test.php プロジェクト: mover-io/phpusable-phpunit
 public function tests()
 {
     PHPUsableTest::$current_test = $this;
     describe('with esperance style assertions', function ($test) {
         describe('with a true value', function ($test) {
             before(function ($test) {
                 //Arbitratry variables can be stored on test to pass between blocks
                 $test->my_value = true;
             });
             it('should be true', function ($test) {
                 $test->expect($test->my_value)->to->be->ok();
             });
         });
         describe('with a false value', function ($test) {
             before(function ($test) {
                 $test->my_value = false;
             });
             it('should be false', function ($test) {
                 $test->expect($test->my_value)->to->be(false);
             });
         });
     });
     describe('with phpunit style assertions', function ($test) {
         describe('with a true value', function ($test) {
             before(function ($test) {
                 $test->my_value = true;
             });
             it('should be true', function ($test) {
                 $test->assertTrue($test->my_value);
             });
         });
         describe('with a false value', function ($test) {
             before(function ($test) {
                 $test->my_value = false;
             });
             it('should be false', function ($test) {
                 $test->assertFalse($test->my_value);
             });
         });
     });
     describe('with mock expectations', function ($test) {
         before(function ($test) {
             $test->mock = $test->getMock('simple_mock', array('test_method'));
             $test->mock->expects($test->once())->method('test_method')->will($test->returnValue('hello world!'));
         });
         it('should return the expected value', function ($test) {
             $test->assertEquals($test->mock->test_method(), 'hello world!');
         });
         it('should fail when it is not called', function ($test) {
             $test->markTestIncomplete('Some graceful manner needs to be found to indicate that this is expected to fail');
         });
     });
     describe('with expected exceptions', function ($test) {
         it('should not error out', function ($test) {
             $test->setExpectedException('Exception');
             throw new \Exception();
         });
     });
     describe('disabled specs', function ($test) {
         it('should not get fatal, without test body');
         xit('should not error out with xit', function ($test) {
             throw new \Exception();
         });
         describe('entry describe without body');
         xdescribe('entry describe with x', function ($test) {
             it('should not error out with it', function ($test) {
                 throw new \Exception();
             });
             describe('inner describe', function ($test) {
                 it('should be also disabled', function ($test) {
                     throw new \Exception();
                 });
             });
             describe('multiple inner describe', function ($test) {
                 it('should be also disabled', function ($test) {
                     throw new \Exception();
                 });
             });
         });
         it('should not stack on disabled state', function ($test) {
             $test->assertTrue(true);
         });
         it('should also mark incomplete when it does not have any expectation', function ($test) {
         });
     });
     describe('should use when method', function ($test) {
         when('there are several case with the same result', function ($test) {
             $test->assertTrue(true);
         });
     });
 }
コード例 #25
0
ファイル: feed.php プロジェクト: quanganhdo/chyrp
        <title type="html">
			<?php 
    echo $post->feather == 'text' ? '☃ ' : '';
    echo fix(oneof($title, ucfirst($post->feather)));
    ?>
		</title>
        <id>tag:<?php 
    echo $tagged;
    ?>
</id>
        <updated><?php 
    echo when("c", $updated);
    ?>
</updated>
        <published><?php 
    echo when("c", $post->created_at);
    ?>
</published>
        <link rel="alternate" type="<?php 
    echo $theme->type;
    ?>
" href="<?php 
    echo fix($url);
    ?>
" />
        <author>
            <name><?php 
    echo fix($author);
    ?>
</name>
<?php 
コード例 #26
0
<?php

use FileSystem\Directory;
use FileSystem\FileSystem;
when('i want to make a new directory', then(apply(a(function (FileSystem $fileSystem, Directory $directory) {
    $fileSystem->make($directory);
}))));
コード例 #27
0
ファイル: ago.php プロジェクト: piiskop/pstk
function when($parameters)
{
    // $parameters = ['timestamp'], ['numberOfUnits']
    $currentTime = time();
    if (preg_match('/\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}/u', $parameters['timestamp'])) {
        $time = strtotime($parameters['timestamp']);
        //konventeerib sekunditeks
    } else {
        $time = $parameters['timestamp'];
    }
    if ($currentTime > $time) {
        $difference = $currentTime - $time;
    } else {
        $difference = $time - $currentTime;
    }
    $units = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
    $secondsInSecond = 1;
    $secondsInMinute = 60;
    $secondsInHour = $secondsInMinute * 60;
    $secondsInDay = $secondsInHour * 24;
    $secondsInWeek = $secondsInDay * 7;
    $secondsInMonth = $secondsInWeek * (4 + 1 / 3);
    $secondsInYear = $secondsInMonth * 12;
    $secondsInDecade = $secondsInYear * 10;
    $sizes = array($secondsInSecond, $secondsInMinute, $secondsInHour, $secondsInDay, $secondsInWeek, $secondsInMonth, $secondsInYear, $secondsInDecade);
    for ($positionInUnits = sizeof($sizes) - 1; $positionInUnits >= 0 && ($amountOfTime = $difference / $sizes[$positionInUnits]) <= 1; $positionInUnits--) {
    }
    if ($positionInUnits < 0) {
        $positionInUnits = 0;
    }
    $remainedTime = $currentTime - $difference % $sizes[$positionInUnits];
    $amountOfTime = floor($amountOfTime);
    if ($amountOfTime != 1) {
        $units[$positionInUnits] .= 's';
    }
    $when = sprintf("%d %s ", $amountOfTime, $units[$positionInUnits]);
    if ($parameters['numberOfUnits'] == 0 && $positionInUnits >= 1 && $currentTime - $remainedTime > 0) {
        $when .= when($remainedTime);
    }
    return $when;
}
コード例 #28
0
ファイル: xmlrpc.php プロジェクト: relisher/chyrp
 private function convertFromDateCreated($args)
 {
     if (array_key_exists('dateCreated', $args)) {
         return when('Y-m-d H:i:s', $args['dateCreated']->getIso());
     } else {
         return null;
     }
 }
コード例 #29
0
<?php

use FileSystem\FileSystem;
use FileSystem\File;
when('i want to delete a file', then(apply(a(function (FileSystem $fileSystem, File $file) {
    $fileSystem->delete($file);
    echo $file->content;
}))));
/*
|--------------------------------------------------------------------------
| Note: The file stays intact.
|--------------------------------------------------------------------------
|
| After you call delete with $file on the file system it goes
| through the delete process of the file system, it is being 
| removed from the file tree and it is removed from the 
| parent inside the file tree. 
|
| BUT: The file stays intact, all its data and even the parent
| will stay intact meaning you can do with that file whatever
| you want.
*/
コード例 #30
0
ファイル: Main.php プロジェクト: vito/chyrp-site
 /**
  * Function: archive
  * Grabs the posts for the Archive page when viewing a year or a month.
  */
 public function archive()
 {
     fallback($_GET['year']);
     fallback($_GET['month']);
     fallback($_GET['day']);
     if (isset($_GET['year']) and isset($_GET['month']) and isset($_GET['day'])) {
         $posts = new Paginator(Post::find(array("placeholders" => true, "where" => array("YEAR(created_at)" => $_GET['year'], "MONTH(created_at)" => $_GET['month'], "DAY(created_at)" => $_GET['day']))), $this->post_limit);
     } elseif (isset($_GET['year']) and isset($_GET['month'])) {
         $posts = new Paginator(Post::find(array("placeholders" => true, "where" => array("YEAR(created_at)" => $_GET['year'], "MONTH(created_at)" => $_GET['month']))), $this->post_limit);
     }
     $sql = SQL::current();
     if (empty($_GET['year']) or empty($_GET['month'])) {
         if (!empty($_GET['year'])) {
             $timestamps = $sql->select("posts", array("DISTINCT YEAR(created_at) AS year", "MONTH(created_at) AS month", "created_at AS created_at", "id"), array("YEAR(created_at)" => $_GET['year']), array("created_at DESC", "id DESC"), array(), null, null, array("YEAR(created_at)", "MONTH(created_at)", "created_at", "id"));
         } else {
             $timestamps = $sql->select("posts", array("DISTINCT YEAR(created_at) AS year", "MONTH(created_at) AS month", "created_at AS created_at", "id"), null, array("created_at DESC", "id DESC"), array(), null, null, array("YEAR(created_at)", "MONTH(created_at)", "created_at", "id"));
         }
         $archives = array();
         $archive_hierarchy = array();
         while ($time = $timestamps->fetchObject()) {
             $year = mktime(0, 0, 0, 1, 0, $time->year);
             $month = mktime(0, 0, 0, $time->month + 1, 0, $time->year);
             $posts = Post::find(array("where" => array("YEAR(created_at)" => when("Y", $time->created_at), "MONTH(created_at)" => when("m", $time->created_at))));
             $archives[$month] = array("posts" => $posts, "year" => $time->year, "month" => strftime("%B", $month), "timestamp" => $month, "url" => url("archive/" . when("Y/m/", $time->created_at)));
             $archive_hierarchy[$year][$month] = $posts;
         }
         $this->display("pages/archive", array("archives" => $archives, "archive_hierarchy" => $archive_hierarchy), __("Archive"));
     } else {
         if (!is_numeric($_GET['year']) or !is_numeric($_GET['month'])) {
             error(__("Error"), __("Please enter a valid year and month."));
         }
         $timestamp = mktime(0, 0, 0, $_GET['month'], oneof(@$_GET['day'], 1), $_GET['year']);
         $depth = isset($_GET['day']) ? "day" : (isset($_GET['month']) ? "month" : (isset($_GET['year']) ? "year" : ""));
         $this->display("pages/archive", array("posts" => $posts, "archive" => array("year" => $_GET['year'], "month" => strftime("%B", $timestamp), "day" => strftime("%d", $timestamp), "timestamp" => $timestamp, "depth" => $depth)), _f("Archive of %s", array(strftime("%B %Y", $timestamp))));
     }
 }