content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
PHP | PHP | fix inconsistent data referencing in view | a3cbe24b6e699f59fcf17b5679b99ab26888deb3 | <ide><path>laravel/view.php
<ide> public function offsetUnset($offset)
<ide> */
<ide> public function __get($key)
<ide> {
<del> return $this[$key];
<add> return $this->data[$key];
<ide> }
<ide>
<ide> /**
<ide> * Magic Method for handling the dynamic setting of data.
<ide> */
<ide> public function __set($key, $value)
<ide> {
<del> $this[$key] = $value;
<add> $this->data[$key] = $value;
<add> }
<add>
<add> /**
<add> * Magic Method for checking dynamically-set data.
<add> */
<add> public function __isset($key)
<add> {
<add> return isset($this->data[$key]);
<ide> }
<ide>
<ide> /** | 1 |
Mixed | Javascript | remove deprecated crypto._tobuf | bf3cb3f9b1be5f55c93493e80e3a9bf41093e18f | <ide><path>doc/api/deprecations.md
<ide> release.
<ide> ### DEP0114: crypto._toBuf()
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/???
<add> description: End-of-Life.
<ide> - version: v11.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/22501
<ide> description: Runtime deprecation.
<ide> -->
<ide>
<del>Type: Runtime
<add>Type: End-Of-Life
<ide>
<ide> The `crypto._toBuf()` function was not designed to be used by modules outside
<del>of Node.js core and will be removed in the future.
<add>of Node.js core and was removed.
<ide>
<ide> <a id="DEP0115"></a>
<ide> ### DEP0115: crypto.prng(), crypto.pseudoRandomBytes(), crypto.rng()
<ide><path>lib/crypto.js
<ide> const {
<ide> getHashes,
<ide> setDefaultEncoding,
<ide> setEngine,
<del> timingSafeEqual,
<del> toBuf
<add> timingSafeEqual
<ide> } = require('internal/crypto/util');
<ide> const Certificate = require('internal/crypto/certificate');
<ide>
<ide> function getFipsForced() {
<ide> }
<ide>
<ide> Object.defineProperties(exports, {
<del> _toBuf: {
<del> enumerable: false,
<del> value: deprecate(toBuf, 'crypto._toBuf is deprecated.', 'DEP0114')
<del> },
<ide> createCipher: {
<ide> enumerable: false,
<ide> value: deprecate(createCipher,
<ide><path>test/parallel/test-crypto.js
<ide> if (!common.hasCrypto)
<ide>
<ide> common.expectWarning({
<ide> DeprecationWarning: [
<del> ['crypto.createCipher is deprecated.', 'DEP0106'],
<del> ['crypto._toBuf is deprecated.', 'DEP0114']
<add> ['crypto.createCipher is deprecated.', 'DEP0106']
<ide> ]
<ide> });
<ide>
<ide> testEncoding({
<ide> testEncoding({
<ide> defaultEncoding: 'latin1'
<ide> }, assertionHashLatin1);
<del>
<del>{
<del> // Test that the exported _toBuf function is deprecated.
<del> crypto._toBuf(Buffer.alloc(0));
<del>} | 3 |
PHP | PHP | fix small typo | be674c9d0d92ccabe98baa13b15af8c0c671408b | <ide><path>src/Http/ServerRequest.php
<ide> public function withCookieParams(array $cookies)
<ide> * Get the parsed request body data.
<ide> *
<ide> * If the request Content-Type is either application/x-www-form-urlencoded
<del> * or multipart/form-data, nd the request method is POST, this will be the
<add> * or multipart/form-data, and the request method is POST, this will be the
<ide> * post data. For other content types, it may be the deserialized request
<ide> * body.
<ide> * | 1 |
Ruby | Ruby | build an ast rather than build sql strings | 186a1b11449a2b94030791b2c778a76b07bb099f | <ide><path>activerecord/lib/active_record/association_preload.rb
<ide> def construct_id_map(records, primary_key=nil)
<ide> end
<ide>
<ide> def preload_has_and_belongs_to_many_association(records, reflection, preload_options={})
<add>
<add> left = reflection.klass.arel_table
<add>
<ide> table_name = reflection.klass.quoted_table_name
<ide> id_to_record_map, ids = construct_id_map(records)
<ide> records.each {|record| record.send(reflection.name).loaded}
<ide> def preload_has_and_belongs_to_many_association(records, reflection, preload_opt
<ide> conditions = "t0.#{reflection.primary_key_name} #{in_or_equals_for_ids(ids)}"
<ide> conditions << append_conditions(reflection, preload_options)
<ide>
<add> right = Arel::Table.new(options[:join_table]).alias('t0')
<add> condition = left[reflection.klass.primary_key].eq(
<add> right[reflection.association_foreign_key])
<add>
<add> join = left.create_join(right, left.create_on(condition))
<add>
<ide> associated_records_proxy = reflection.klass.unscoped.
<ide> includes(options[:include]).
<del> joins("INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}").
<add> joins(join).
<ide> select("#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id").
<ide> order(options[:order])
<ide> | 1 |
Text | Text | add customized text to widget | 94320c5b81af08bfd8d55d6b0cd9d9442c55f29f | <ide><path>model_cards/mrm8488/electricidad-base-generator/README.md
<ide> ---
<ide> language: es
<ide> thumbnail: https://i.imgur.com/uxAvBfh.png
<add>widget:
<add>- text: "Madrid es una ciudad muy [MASK] en España."
<ide>
<ide>
<ide> --- | 1 |
Text | Text | add model cards for microsoft's minilm | 866a8ccabb74231fb3f5ea547f213b1d5cffaf8d | <ide><path>model_cards/microsoft/MiniLM-L12-H384-uncased/README.md
<add>---
<add>thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
<add>tags:
<add>- text-classification
<add>license: mit
<add>---
<add>
<add>## MiniLM: Small and Fast Pre-trained Models for Language Understanding and Generation
<add>
<add>MiniLM is a distilled model from the paper "[MiniLM: Deep Self-Attention Distillation for Task-Agnostic Compression of Pre-Trained Transformers](https://arxiv.org/abs/2002.10957)".
<add>
<add>Please find the information about preprocessing, training and full details of the MiniLM in the [original MiniLM repository](https://github.com/microsoft/unilm/blob/master/minilm/).
<add>
<add>Please note: This checkpoint can be an inplace substitution for BERT and it needs to be fine-tuned before use!
<add>
<add>### English Pre-trained Models
<add>We release the **uncased** **12**-layer model with **384** hidden size distilled from an in-house pre-trained [UniLM v2](/unilm) model in BERT-Base size.
<add>
<add>- MiniLMv1-L12-H384-uncased: 12-layer, 384-hidden, 12-heads, 33M parameters, 2.7x faster than BERT-Base
<add>
<add>#### Fine-tuning on NLU tasks
<add>
<add>We present the dev results on SQuAD 2.0 and several GLUE benchmark tasks.
<add>
<add>| Model | #Param | SQuAD 2.0 | MNLI-m | SST-2 | QNLI | CoLA | RTE | MRPC | QQP |
<add>|---------------------------------------------------|--------|-----------|--------|-------|------|------|------|------|------|
<add>| [BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 109M | 76.8 | 84.5 | 93.2 | 91.7 | 58.9 | 68.6 | 87.3 | 91.3 |
<add>| **MiniLM-L12xH384** | 33M | 81.7 | 85.7 | 93.0 | 91.5 | 58.5 | 73.3 | 89.5 | 91.3 |
<add>
<add>### Citation
<add>
<add>If you find MiniLM useful in your research, please cite the following paper:
<add>
<add>``` latex
<add>@misc{wang2020minilm,
<add> title={MiniLM: Deep Self-Attention Distillation for Task-Agnostic Compression of Pre-Trained Transformers},
<add> author={Wenhui Wang and Furu Wei and Li Dong and Hangbo Bao and Nan Yang and Ming Zhou},
<add> year={2020},
<add> eprint={2002.10957},
<add> archivePrefix={arXiv},
<add> primaryClass={cs.CL}
<add>}
<add>```
<ide><path>model_cards/microsoft/Multilingual-MiniLM-L12-H384/README.md
<add>---
<add>thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
<add>tags:
<add>- text-classification
<add>license: mit
<add>---
<add>
<add>## MiniLM: Small and Fast Pre-trained Models for Language Understanding and Generation
<add>
<add>MiniLM is a distilled model from the paper "[MiniLM: Deep Self-Attention Distillation for Task-Agnostic Compression of Pre-Trained Transformers](https://arxiv.org/abs/2002.10957)".
<add>
<add>Please find the information about preprocessing, training and full details of the MiniLM in the [original MiniLM repository](https://github.com/microsoft/unilm/blob/master/minilm/).
<add>
<add>Please note: This checkpoint uses `BertModel` with `XLMRobertaTokenizer` so `AutoTokenizer` won't work with this checkpoint!
<add>
<add>### Multilingual Pretrained Model
<add>- Multilingual-MiniLMv1-L12-H384: 12-layer, 384-hidden, 12-heads, 21M Transformer parameters, 96M embedding parameters
<add>
<add>Multilingual MiniLM uses the same tokenizer as XLM-R. But the Transformer architecture of our model is the same as BERT. We provide the fine-tuning code on XNLI based on [huggingface/transformers](https://github.com/huggingface/transformers). Please replace `run_xnli.py` in transformers with [ours](https://github.com/microsoft/unilm/blob/master/minilm/examples/run_xnli.py) to fine-tune multilingual MiniLM.
<add>
<add>We evaluate the multilingual MiniLM on cross-lingual natural language inference benchmark (XNLI) and cross-lingual question answering benchmark (MLQA).
<add>
<add>#### Cross-Lingual Natural Language Inference - [XNLI](https://arxiv.org/abs/1809.05053)
<add>
<add>We evaluate our model on cross-lingual transfer from English to other languages. Following [Conneau et al. (2019)](https://arxiv.org/abs/1911.02116), we select the best single model on the joint dev set of all the languages.
<add>
<add>| Model | #Layers | #Hidden | #Transformer Parameters | Average | en | fr | es | de | el | bg | ru | tr | ar | vi | th | zh | hi | sw | ur |
<add>|---------------------------------------------------------------------------------------------|---------|---------|-------------------------|---------|------|------|------|------|------|------|------|------|------|------|------|------|------|------|------|
<add>| [mBERT](https://github.com/google-research/bert) | 12 | 768 | 85M | 66.3 | 82.1 | 73.8 | 74.3 | 71.1 | 66.4 | 68.9 | 69.0 | 61.6 | 64.9 | 69.5 | 55.8 | 69.3 | 60.0 | 50.4 | 58.0 |
<add>| [XLM-100](https://github.com/facebookresearch/XLM#pretrained-cross-lingual-language-models) | 16 | 1280 | 315M | 70.7 | 83.2 | 76.7 | 77.7 | 74.0 | 72.7 | 74.1 | 72.7 | 68.7 | 68.6 | 72.9 | 68.9 | 72.5 | 65.6 | 58.2 | 62.4 |
<add>| [XLM-R Base](https://arxiv.org/abs/1911.02116) | 12 | 768 | 85M | 74.5 | 84.6 | 78.4 | 78.9 | 76.8 | 75.9 | 77.3 | 75.4 | 73.2 | 71.5 | 75.4 | 72.5 | 74.9 | 71.1 | 65.2 | 66.5 |
<add>| **mMiniLM-L12xH384** | 12 | 384 | 21M | 71.1 | 81.5 | 74.8 | 75.7 | 72.9 | 73.0 | 74.5 | 71.3 | 69.7 | 68.8 | 72.1 | 67.8 | 70.0 | 66.2 | 63.3 | 64.2 |
<add>
<add>This example code fine-tunes **12**-layer multilingual MiniLM on XNLI.
<add>
<add>```bash
<add># run fine-tuning on XNLI
<add>DATA_DIR=/{path_of_data}/
<add>OUTPUT_DIR=/{path_of_fine-tuned_model}/
<add>MODEL_PATH=/{path_of_pre-trained_model}/
<add>
<add>python ./examples/run_xnli.py --model_type minilm \
<add> --output_dir ${OUTPUT_DIR} --data_dir ${DATA_DIR} \
<add> --model_name_or_path microsoft/Multilingual-MiniLM-L12-H384 \
<add> --tokenizer_name xlm-roberta-base \
<add> --config_name ${MODEL_PATH}/multilingual-minilm-l12-h384-config.json \
<add> --do_train \
<add> --do_eval \
<add> --max_seq_length 128 \
<add> --per_gpu_train_batch_size 128 \
<add> --learning_rate 5e-5 \
<add> --num_train_epochs 5 \
<add> --per_gpu_eval_batch_size 32 \
<add> --weight_decay 0.001 \
<add> --warmup_steps 500 \
<add> --save_steps 1500 \
<add> --logging_steps 1500 \
<add> --eval_all_checkpoints \
<add> --language en \
<add> --fp16 \
<add> --fp16_opt_level O2
<add>```
<add>
<add>#### Cross-Lingual Question Answering - [MLQA](https://arxiv.org/abs/1910.07475)
<add>
<add>Following [Lewis et al. (2019b)](https://arxiv.org/abs/1910.07475), we adopt SQuAD 1.1 as training data and use MLQA English development data for early stopping.
<add>
<add>| Model F1 Score | #Layers | #Hidden | #Transformer Parameters | Average | en | es | de | ar | hi | vi | zh |
<add>|--------------------------------------------------------------------------------------------|---------|---------|-------------------------|---------|------|------|------|------|------|------|------|
<add>| [mBERT](https://github.com/google-research/bert) | 12 | 768 | 85M | 57.7 | 77.7 | 64.3 | 57.9 | 45.7 | 43.8 | 57.1 | 57.5 |
<add>| [XLM-15](https://github.com/facebookresearch/XLM#pretrained-cross-lingual-language-models) | 12 | 1024 | 151M | 61.6 | 74.9 | 68.0 | 62.2 | 54.8 | 48.8 | 61.4 | 61.1 |
<add>| [XLM-R Base](https://arxiv.org/abs/1911.02116) (Reported) | 12 | 768 | 85M | 62.9 | 77.8 | 67.2 | 60.8 | 53.0 | 57.9 | 63.1 | 60.2 |
<add>| [XLM-R Base](https://arxiv.org/abs/1911.02116) (Our fine-tuned) | 12 | 768 | 85M | 64.9 | 80.3 | 67.0 | 62.7 | 55.0 | 60.4 | 66.5 | 62.3 |
<add>| **mMiniLM-L12xH384** | 12 | 384 | 21M | 63.2 | 79.4 | 66.1 | 61.2 | 54.9 | 58.5 | 63.1 | 59.0 |
<add>
<add>### Citation
<add>
<add>If you find MiniLM useful in your research, please cite the following paper:
<add>
<add>``` latex
<add>@misc{wang2020minilm,
<add> title={MiniLM: Deep Self-Attention Distillation for Task-Agnostic Compression of Pre-Trained Transformers},
<add> author={Wenhui Wang and Furu Wei and Li Dong and Hangbo Bao and Nan Yang and Ming Zhou},
<add> year={2020},
<add> eprint={2002.10957},
<add> archivePrefix={arXiv},
<add> primaryClass={cs.CL}
<add>}
<add>``` | 2 |
Python | Python | remove a redundant "the" in a comment | d4f6734741929f7532c03b00e732bf7db42f7c01 | <ide><path>flask/helpers.py
<ide> def send_file(filename_or_fp, mimetype=None, as_attachment=False,
<ide> rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
<ide> direct_passthrough=True)
<ide>
<del> # if we know the file modification date, we can store it as the
<add> # if we know the file modification date, we can store it as
<ide> # the time of the last modification.
<ide> if mtime is not None:
<ide> rv.last_modified = int(mtime) | 1 |
Javascript | Javascript | destroy socket when encrypted side closes | 164d5b3465571a88da59cdddc03bb869126548eb | <ide><path>lib/tls.js
<ide> function pipe(pair, socket) {
<ide> pair.encrypted.pipe(socket);
<ide> socket.pipe(pair.encrypted);
<ide>
<add> pair.encrypted.on('close', function() {
<add> process.nextTick(function() {
<add> socket.destroy();
<add> });
<add> });
<add>
<ide> pair.fd = socket.fd;
<ide> var cleartext = pair.cleartext;
<ide> cleartext.socket = socket; | 1 |
Go | Go | fix configuration test for mknod | f80fd5da09013d7cd25a0f246ffffd7b6c064073 | <ide><path>runtime/execdriver/native/template/default_template.go
<ide> import (
<ide>
<ide> // New returns the docker default configuration for libcontainer
<ide> func New() *libcontainer.Container {
<del> return &libcontainer.Container{
<add> container := &libcontainer.Container{
<ide> CapabilitiesMask: libcontainer.Capabilities{
<ide> libcontainer.GetCapability("SETPCAP"),
<ide> libcontainer.GetCapability("SYS_MODULE"),
<ide> func New() *libcontainer.Container {
<ide> libcontainer.GetCapability("MAC_OVERRIDE"),
<ide> libcontainer.GetCapability("MAC_ADMIN"),
<ide> libcontainer.GetCapability("NET_ADMIN"),
<add> libcontainer.GetCapability("MKNOD"),
<ide> },
<ide> Namespaces: libcontainer.Namespaces{
<ide> libcontainer.GetNamespace("NEWNS"),
<ide> func New() *libcontainer.Container {
<ide> "apparmor_profile": "docker-default",
<ide> },
<ide> }
<add> container.CapabilitiesMask.Get("MKNOD").Enabled = true
<add> return container
<ide> } | 1 |
PHP | PHP | fix @param directives for cache store | 15d4384e041bcc458ae6443a6becab1d995be60c | <ide><path>src/Illuminate/Contracts/Cache/Store.php
<ide> public function many(array $keys);
<ide> * Store an item in the cache for a given number of minutes.
<ide> *
<ide> * @param string $key
<del> * @param mixed $value
<add> * @param mixed $value
<ide> * @param float|int $minutes
<ide> * @return void
<ide> */
<ide> public function putMany(array $values, $minutes);
<ide> * Increment the value of an item in the cache.
<ide> *
<ide> * @param string $key
<del> * @param mixed $value
<add> * @param mixed $value
<ide> * @return int|bool
<ide> */
<ide> public function increment($key, $value = 1);
<ide> public function increment($key, $value = 1);
<ide> * Decrement the value of an item in the cache.
<ide> *
<ide> * @param string $key
<del> * @param mixed $value
<add> * @param mixed $value
<ide> * @return int|bool
<ide> */
<ide> public function decrement($key, $value = 1);
<ide> public function decrement($key, $value = 1);
<ide> * Store an item in the cache indefinitely.
<ide> *
<ide> * @param string $key
<del> * @param mixed $value
<add> * @param mixed $value
<ide> * @return void
<ide> */
<ide> public function forever($key, $value); | 1 |
PHP | PHP | remove duplicate call to baketest | dc7fcb994fb42cb51051542768cfa9d28256cb2d | <ide><path>src/Console/Command/Task/ControllerTask.php
<ide> public function all() {
<ide> foreach ($this->listAll() as $table) {
<ide> $controller = $this->_controllerName($table);
<ide> $this->bake($controller);
<del> $this->bakeTest($controller);
<ide> $controllersCreated++;
<ide> }
<ide> } | 1 |
Python | Python | add load_vectors_into_model util | df95e2af64a6c3d2862e4317a450e8e694e2d406 | <ide><path>spacy/util.py
<ide> def get_module_path(module: ModuleType) -> Path:
<ide> return Path(sys.modules[module.__module__].__file__).parent
<ide>
<ide>
<add>def load_vectors_into_model(
<add> nlp: "Language",
<add> name: Union[str, Path],
<add> *,
<add> add_strings=True
<add>) -> None:
<add> """Load word vectors from an installed model or path into a model instance."""
<add> vectors_nlp = load_model(name)
<add> nlp.vocab.vectors = vectors_nlp.vocab.vectors
<add> if add_strings:
<add> # I guess we should add the strings from the vectors_nlp model?
<add> # E.g. if someone does a similarity query, they might expect the strings.
<add> for key in nlp.vocab.vectors.key2row:
<add> if key in vectors_nlp.strings:
<add> nlp.vocab.strings.add(vectors_nlp.strings[key])
<add>
<add>
<ide> def load_model(
<ide> name: Union[str, Path],
<ide> disable: Iterable[str] = tuple(), | 1 |
Go | Go | move sandbox resources when container restarts | 1ffe6fef0297e5ef82bdc91774917a52e47531d9 | <ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) SetKey(basePath string) error {
<ide> }
<ide>
<ide> sb.Lock()
<del> if sb.osSbox != nil {
<del> sb.Unlock()
<del> return types.ForbiddenErrorf("failed to set sandbox key : already assigned")
<del> }
<add> osSbox := sb.osSbox
<ide> sb.Unlock()
<del> osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
<add>
<add> if osSbox != nil {
<add> // If we already have an OS sandbox, release the network resources from that
<add> // and destroy the OS snab. We are moving into a new home further down. Note that none
<add> // of the network resources gets destroyed during the move.
<add> sb.releaseOSSbox()
<add> }
<add>
<add> osSbox, err = osl.GetSandboxForExternalKey(basePath, sb.Key())
<ide> if err != nil {
<ide> return err
<ide> }
<add>
<ide> sb.Lock()
<ide> sb.osSbox = osSbox
<ide> sb.Unlock()
<ide> func (sb *sandbox) SetKey(basePath string) error {
<ide> return nil
<ide> }
<ide>
<add>func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
<add> for _, i := range osSbox.Info().Interfaces() {
<add> // Only remove the interfaces owned by this endpoint from the sandbox.
<add> if ep.hasInterface(i.SrcName()) {
<add> if err := i.Remove(); err != nil {
<add> log.Debugf("Remove interface failed: %v", err)
<add> }
<add> }
<add> }
<add>
<add> ep.Lock()
<add> joinInfo := ep.joinInfo
<add> ep.Unlock()
<add>
<add> // Remove non-interface routes.
<add> for _, r := range joinInfo.StaticRoutes {
<add> if err := osSbox.RemoveStaticRoute(r); err != nil {
<add> log.Debugf("Remove route failed: %v", err)
<add> }
<add> }
<add>}
<add>
<add>func (sb *sandbox) releaseOSSbox() {
<add> sb.Lock()
<add> osSbox := sb.osSbox
<add> sb.osSbox = nil
<add> sb.Unlock()
<add>
<add> if osSbox == nil {
<add> return
<add> }
<add>
<add> for _, ep := range sb.getConnectedEndpoints() {
<add> releaseOSSboxResources(osSbox, ep)
<add> }
<add>
<add> osSbox.Destroy()
<add>}
<add>
<ide> func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
<ide> sb.Lock()
<ide> if sb.osSbox == nil {
<ide> func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
<ide> osSbox := sb.osSbox
<ide> sb.Unlock()
<ide> if osSbox != nil {
<del> for _, i := range osSbox.Info().Interfaces() {
<del> // Only remove the interfaces owned by this endpoint from the sandbox.
<del> if ep.hasInterface(i.SrcName()) {
<del> if err := i.Remove(); err != nil {
<del> log.Debugf("Remove interface failed: %v", err)
<del> }
<del> }
<del> }
<del>
<del> ep.Lock()
<del> joinInfo := ep.joinInfo
<del> ep.Unlock()
<del>
<del> // Remove non-interface routes.
<del> for _, r := range joinInfo.StaticRoutes {
<del> if err := osSbox.RemoveStaticRoute(r); err != nil {
<del> log.Debugf("Remove route failed: %v", err)
<del> }
<del> }
<add> releaseOSSboxResources(osSbox, ep)
<ide> }
<ide>
<ide> sb.Lock() | 1 |
Python | Python | add test for negative axis values in np.insert | 496813f1a23363bbd50a62a60c37f6bd4e10649b | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_multidim(self):
<ide> assert_equal(insert(a[:,:1], 1, a[:,1], axis=1), a)
<ide> assert_equal(insert(a[:1,:], 1, a[1,:], axis=0), a)
<ide>
<add> # negative axis value
<add> a = np.arange(24).reshape((2,3,4))
<add> assert_equal(insert(a, 1, a[:,:,3], axis=-1),
<add> insert(a, 1, a[:,:,3], axis=2))
<add> assert_equal(insert(a, 1, a[:,2,:], axis=-2),
<add> insert(a, 1, a[:,2,:], axis=1))
<add>
<ide> def test_0d(self):
<ide> # This is an error in the future
<ide> a = np.array(1) | 1 |
Mixed | PHP | fix some typos | a8a55657a588291693b1faa93d1e6ebdb556b113 | <ide><path>CHANGELOG-5.2.md
<ide> - Simplified calling `Model::replicate()` with `$except` argument ([#13676](https://github.com/laravel/framework/pull/13676))
<ide> - Allow auth events to be serialized ([#13704](https://github.com/laravel/framework/pull/13704))
<ide> - Added `for` and `id` attributes to auth scaffold ([#13689](https://github.com/laravel/framework/pull/13689))
<del>- Aquire lock before deleting reserved job ([4b502dc](https://github.com/laravel/framework/commit/4b502dc6eecd80efad01e845469b9a2bac26dae0#diff-b05083dc38b4e45d38d28c676abbad83))
<add>- Acquire lock before deleting reserved job ([4b502dc](https://github.com/laravel/framework/commit/4b502dc6eecd80efad01e845469b9a2bac26dae0#diff-b05083dc38b4e45d38d28c676abbad83))
<ide>
<ide> ### Fixed
<ide> - Prefix timestamps when updating many-to-many relationships ([#13519](https://github.com/laravel/framework/pull/13519))
<ide><path>src/Illuminate/Database/Events/QueryExecuted.php
<ide> class QueryExecuted
<ide> public $time;
<ide>
<ide> /**
<del> * The databse connection instance.
<add> * The database connection instance.
<ide> *
<ide> * @var \Illuminate\Database\Connection
<ide> */
<ide><path>src/Illuminate/Queue/SyncQueue.php
<ide> public function push($job, $data = '', $queue = null)
<ide> }
<ide>
<ide> /**
<del> * Handle an exception that occured while processing a job.
<add> * Handle an exception that occurred while processing a job.
<ide> *
<ide> * @param \Illuminate\Queue\Jobs\Job $queueJob
<ide> * @param \Exception $e | 3 |
Java | Java | fix one failing test and @ignore another | 9ac71afbdaa3e9364680b0e396a27b36229e4220 | <ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java
<ide> import java.util.Map;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> public void decodeToFlux() throws Exception {
<ide> @Test
<ide> public void decodeEmptyArrayToFlux() throws Exception {
<ide> Flux<DataBuffer> source = Flux.just(stringBuffer("[]"));
<del>
<ide> ResolvableType elementType = forClass(Pojo.class);
<del> Flux<Object> flux = new Jackson2JsonDecoder().decode(source, elementType, null,
<del> emptyMap());
<add> Flux<Object> flux = new Jackson2JsonDecoder().decode(source, elementType, null, emptyMap());
<ide>
<ide> StepVerifier.create(flux)
<ide> .expectNextCount(0)
<ide> public void classLevelJsonView() throws Exception {
<ide> public void decodeEmptyBodyToMono() throws Exception {
<ide> Flux<DataBuffer> source = Flux.empty();
<ide> ResolvableType elementType = forClass(Pojo.class);
<del> Mono<Object> mono = new Jackson2JsonDecoder().decodeToMono(source, elementType,
<del> null, emptyMap());
<add> Mono<Object> mono = new Jackson2JsonDecoder().decodeToMono(source, elementType, null, emptyMap());
<ide>
<ide> StepVerifier.create(mono)
<ide> .expectNextCount(0)
<ide> .verifyComplete();
<ide> }
<ide>
<ide> @Test
<add> @Ignore
<ide> public void decodeEmptyArrayToMono() throws Exception {
<ide> Flux<DataBuffer> source = Flux.just(stringBuffer("[]"));
<ide> ResolvableType elementType = forClass(Pojo.class);
<del> Mono<Object> mono = new Jackson2JsonDecoder().decodeToMono(source, elementType,
<del> null, emptyMap());
<add> Mono<Object> mono = new Jackson2JsonDecoder().decodeToMono(source, elementType, null, emptyMap());
<ide>
<ide> StepVerifier.create(mono)
<ide> .expectNextCount(0)
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java
<ide> public void unresolvedViewName() throws Exception {
<ide>
<ide> StepVerifier.create(mono)
<ide> .expectNextCount(0)
<del> .expectErrorMessage("Could not resolve view with name 'account'.")
<add> .expectErrorMessage("Could not resolve view with name 'path'.")
<ide> .verify();
<ide> }
<ide> | 2 |
Text | Text | control input examples of geotrend models | eec76615f68248ae65d107d817a9c22e10047b37 | <ide><path>model_cards/Geotrend/bert-base-15lang-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<add>- text: "Paris est la [MASK] de la France."
<add>- text: "Paris est la capitale de la [MASK]."
<add>- text: "L'élection américaine a eu [MASK] en novembre 2020."
<add>- text: "تقع سويسرا في [MASK] أوروبا"
<add>- text: "إسمي محمد وأسكن في [MASK]."
<ide> ---
<ide>
<ide> # bert-base-15lang-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-15lang-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-ar-cased/README.md
<ide> language: ar
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "تقع سويسرا في [MASK] أوروبا"
<add>- text: "إسمي محمد وأسكن في [MASK]."
<ide> ---
<ide>
<ide> # bert-base-ar-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-ar-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-bg-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-bg-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-de-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-de-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-el-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-el-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-ar-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<add>- text: "تقع سويسرا في [MASK] أوروبا"
<add>- text: "إسمي محمد وأسكن في [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-ar-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-ar-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-bg-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-bg-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-bg-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-cased/README.md
<ide> language: en
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-de-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-de-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-de-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-el-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-el-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-el-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-es-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-es-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-es-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-fr-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<add>- text: "Paris est la [MASK] de la France."
<add>- text: "Paris est la capitale de la [MASK]."
<add>- text: "L'élection américaine a eu [MASK] en novembre 2020."
<ide> ---
<ide>
<ide> # bert-base-en-fr-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-fr-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-hi-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-hi-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-hi-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-ru-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-ru-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-ru-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-sw-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-sw-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-sw-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-th-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-th-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-th-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-tr-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-tr-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-tr-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-ur-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-ur-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-ur-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-vi-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-vi-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-vi-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-en-zh-cased/README.md
<ide> language: multilingual
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Google generated 46 billion [MASK] in revenue."
<add>- text: "Paris is the capital of [MASK]."
<add>- text: "Algiers is the largest city in [MASK]."
<ide> ---
<ide>
<ide> # bert-base-en-zh-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-en-zh-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-es-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-es-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-fr-cased/README.md
<ide> language: fr
<ide> datasets: wikipedia
<ide>
<ide> license: apache-2.0
<add>
<add>widget:
<add>- text: "Paris est la [MASK] de la France."
<add>- text: "Paris est la capitale de la [MASK]."
<add>- text: "L'élection américaine a eu [MASK] en novembre 2020."
<ide> ---
<ide>
<ide> # bert-base-fr-cased
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-fr-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-hi-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-hi-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-ru-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-ru-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-sw-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-sw-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-th-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-th-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-tr-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-tr-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-ur-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-ur-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-vi-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-vi-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex
<ide><path>model_cards/Geotrend/bert-base-zh-cased/README.md
<ide> model = AutoModel.from_pretrained("Geotrend/bert-base-zh-cased")
<ide>
<ide> ```
<ide>
<add>To generate other smaller versions of multilingual transformers please visit [our Github repo](https://github.com/Geotrend-research/smaller-transformers).
<add>
<ide> ### How to cite
<ide>
<ide> ```bibtex | 30 |
Python | Python | add test for currently failing span.as_doc case | 090aed940a8340d20b4ab1cd31637ceae3753cfe | <ide><path>spacy/tests/spans/test_span.py
<ide> def test_span_to_array(doc):
<ide> assert arr[0, 0] == span[0].orth
<ide> assert arr[0, 1] == len(span[0])
<ide>
<add>
<add>@pytest.mark.xfail
<add>def test_span_as_doc(doc):
<add> span = doc[4:10]
<add> span_doc = span.as_doc()
<add> assert span.text == span_doc.text | 1 |
Text | Text | fix several markdown links in slim readme | db223fc1b90c591774dca05827150aad8abce689 | <ide><path>research/inception/inception/slim/README.md
<ide> keeping a model's architecture transparent and its hyperparameters explicit.
<ide> ## Teaser
<ide>
<ide> As a demonstration of the simplicity of using TF-Slim, compare the simplicity of
<del>the code necessary for defining the entire [VGG]
<del>(http://www.robots.ox.ac.uk/~vgg/research/very_deep/) network using TF-Slim to
<add>the code necessary for defining the entire [VGG](http://www.robots.ox.ac.uk/~vgg/research/very_deep/) network using TF-Slim to
<ide> the lengthy and verbose nature of defining just the first three layers (out of
<ide> 16) using native tensorflow:
<ide>
<ide> def vgg16(inputs):
<ide> TF-Slim offers several advantages over just the built-in tensorflow libraries:
<ide>
<ide> * Allows one to define models much more compactly by eliminating boilerplate
<del> code. This is accomplished through the use of [argument scoping](scopes.py)
<del> and numerous high level [operations](ops.py). These tools increase
<add> code. This is accomplished through the use of [argument scoping](./scopes.py)
<add> and numerous high level [operations](./ops.py). These tools increase
<ide> readability and maintainability, reduce the likelihood of an error from
<ide> copy-and-pasting hyperparameter values and simplifies hyperparameter tuning.
<del>* Makes developing models simple by providing commonly used [loss functions]
<del> (losses.py)
<del>* Provides a concise [definition](inception_model.py) of [Inception v3]
<del> (http://arxiv.org/abs/1512.00567) network architecture ready to be used
<add>* Makes developing models simple by providing commonly used [loss functions](./losses.py)
<add>* Provides a concise [definition](./inception_model.py) of [Inception v3](http://arxiv.org/abs/1512.00567) network architecture ready to be used
<ide> out-of-the-box or subsumed into new models.
<ide>
<ide> Additionally TF-Slim was designed with several principles in mind:
<ide> roughly correspond to such layers. These include:
<ide>
<ide> Layer | TF-Slim Op
<ide> --------------------- | ------------------------
<del>Convolutional Layer | [ops.conv2d](ops.py)
<del>Fully Connected Layer | [ops.fc](ops.py)
<del>BatchNorm layer | [ops.batch_norm](ops.py)
<del>Max Pooling Layer | [ops.max_pool](ops.py)
<del>Avg Pooling Layer | [ops.avg_pool](ops.py)
<del>Dropout Layer | [ops.dropout](ops.py)
<add>Convolutional Layer | [ops.conv2d](./ops.py)
<add>Fully Connected Layer | [ops.fc](./ops.py)
<add>BatchNorm layer | [ops.batch_norm](./ops.py)
<add>Max Pooling Layer | [ops.max_pool](./ops.py)
<add>Avg Pooling Layer | [ops.avg_pool](./ops.py)
<add>Dropout Layer | [ops.dropout](./ops.py)
<ide>
<ide> [ops.py](./ops.py) also includes operations that are not really "layers" per se,
<ide> but are often used to manipulate hidden unit representations during inference:
<ide>
<ide> Operation | TF-Slim Op
<ide> --------- | ---------------------
<del>Flatten | [ops.flatten](ops.py)
<add>Flatten | [ops.flatten](./ops.py)
<ide>
<ide> TF-Slim also provides a meta-operation called `repeat_op` that allows one to
<ide> repeatedly perform the same operation. Consider the following snippet from the
<ide> number. More concretely, the scopes in the example above would be 'conv3_1',
<ide>
<ide> ### Scopes
<ide>
<del>In addition to the types of scope mechanisms in TensorFlow ([name_scope]
<del>(https://www.tensorflow.org/api_docs/python/framework.html#name_scope),
<del>[variable_scope]
<del>(https://www.tensorflow.org/api_docs/python/state_ops.html#variable_scope),
<del>TF-Slim adds a new scoping mechanism called "argument scope" or [arg_scope]
<del>(scopes.py). This new scope allows a user to specify one or more operations and
<add>In addition to the types of scope mechanisms in TensorFlow ([name_scope](https://www.tensorflow.org/api_docs/python/framework.html#name_scope),
<add>[variable_scope](https://www.tensorflow.org/api_docs/python/state_ops.html#variable_scope),
<add>TF-Slim adds a new scoping mechanism called "argument scope" or [arg_scope](./scopes.py). This new scope allows a user to specify one or more operations and
<ide> a set of arguments which will be passed to each of the operations defined in the
<ide> `arg_scope`. This functionality is best illustrated by example. Consider the
<ide> following code snippet:
<ide> let TF-Slim know about the additional loss and let TF-Slim handle the losses.
<ide> ## Putting the Pieces Together
<ide>
<ide> By combining TF-Slim Variables, Operations and scopes, we can write a normally
<del>very complex network with very few lines of code. For example, the entire [VGG]
<del>(https://www.robots.ox.ac.uk/~vgg/research/very_deep/) architecture can be
<add>very complex network with very few lines of code. For example, the entire [VGG](https://www.robots.ox.ac.uk/~vgg/research/very_deep/) architecture can be
<ide> defined with just the following snippet:
<ide>
<ide> ```python
<ide> with tf.Session() as sess:
<ide> ...
<ide> ```
<ide>
<del>See [Restoring Variables]
<del>(https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html#restoring-variables)
<del>and [Choosing which Variables to Save and Restore]
<del>(https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html#choosing-which-variables-to-save-and-restore)
<del>sections of the [Variables]
<del>(https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html) page for
<add>See [Restoring Variables](https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html#restoring-variables)
<add>and [Choosing which Variables to Save and Restore](https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html#choosing-which-variables-to-save-and-restore)
<add>sections of the [Variables](https://www.tensorflow.org/versions/r0.7/how_tos/variables/index.html) page for
<ide> more details.
<ide>
<ide> ### Using slim.variables to Track which Variables need to be Restored | 1 |
Text | Text | improve prefetch docs | e35053e8c3788d75a74aa8dce7a8437b8c86166c | <ide><path>packages/next/README.md
<ide> Since Next.js server-renders your pages, this allows all the future interaction
<ide>
<ide> #### With `<Link>`
<ide>
<del>`<Link>` will automatically prefetch pages in the background as they appear in the view.
<add>`<Link>` will automatically prefetch pages in the background as they appear in the view. If certain pages are rarely visited you can manually set `prefetch` to `false`, here's how:
<add>
<add>```jsx
<add><Link href="/about" prefetch={false}>
<add> <a>About</a>
<add></Link>
<add>```
<ide>
<ide> #### Imperatively
<ide> | 1 |
Python | Python | add headers at tls connection | 5c6e50524e29da2a2581b23a2913211dae9e386e | <ide><path>libcloud/container/drivers/docker.py
<ide> def __init__(self, key, secret, secure=False,
<ide> )
<ide> self.cert_file = cert_file
<ide>
<add> def add_default_headers(self, headers):
<add> """
<add> Add parameters that are necessary for every request
<add> If user and password are specified, include a base http auth
<add> header
<add> """
<add> headers['Content-Type'] = 'application/json'
<add> return headers
<add>
<ide>
<ide> class DockerContainerDriver(ContainerDriver):
<ide> """ | 1 |
Ruby | Ruby | add `casks` method to iterate through arguments | 9c8f7138f35625878e017559c896441fda6f357c | <ide><path>Library/Homebrew/cask/lib/hbc/cli/abstract_command.rb
<ide> def self.run(*args)
<ide> def initialize(*args)
<ide> @args = process_arguments(*args)
<ide> end
<add>
<add> def self.warn_unavailable_with_suggestion(cask_token, e)
<add> exact_match, partial_matches = Search.search(cask_token)
<add> error_message = e.message
<add> if exact_match
<add> error_message.concat(" Did you mean:\n#{exact_match}")
<add> elsif !partial_matches.empty?
<add> error_message.concat(" Did you mean one of:\n")
<add> .concat(Formatter.columns(partial_matches.take(20)))
<add> end
<add> onoe error_message
<add> end
<add>
<add> private
<add>
<add> def casks(alternative: -> { [] })
<add> return to_enum(:casks, alternative: alternative) unless block_given?
<add>
<add> count = 0
<add>
<add> casks = args.empty? ? alternative.call : args
<add>
<add> casks.each do |cask_or_token|
<add> begin
<add> yield cask_or_token.respond_to?(:token) ? cask_or_token : CaskLoader.load(cask_or_token)
<add> count += 1
<add> rescue CaskUnavailableError => e
<add> cask_token = cask_or_token
<add> self.class.warn_unavailable_with_suggestion cask_token, e
<add> rescue CaskError => e
<add> onoe e.message
<add> end
<add> end
<add>
<add> return :empty if casks.length.zero?
<add> (count == casks.length) ? :complete : :incomplete
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/cli/audit.rb
<ide> def self.help
<ide> end
<ide>
<ide> def run
<del> casks_to_audit = args.empty? ? Hbc.all : args.map(&CaskLoader.public_method(:load))
<del>
<del> failed_casks = casks_to_audit.reject do |cask|
<del> audit(cask)
<del> end
<add> failed_casks = casks(alternative: -> { Hbc.all })
<add> .reject { |cask| audit(cask) }
<ide>
<ide> return if failed_casks.empty?
<ide> raise CaskError, "audit failed for casks: #{failed_casks.join(" ")}"
<ide><path>Library/Homebrew/cask/lib/hbc/cli/cat.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> args.each do |cask_token|
<del> cask_path = CaskLoader.path(cask_token)
<del> raise CaskUnavailableError, cask_token.to_s unless cask_path.exist?
<del> puts File.open(cask_path, &:read)
<add> raise CaskError, "Cat incomplete." if cat_casks == :incomplete
<add> end
<add>
<add> def cat_casks
<add> casks.each do |cask|
<add> puts File.open(cask.sourcefile_path, &:read)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/cask/lib/hbc/cli/cleanup.rb
<ide> def initialize(*args, cache_location: Hbc.cache)
<ide> end
<ide>
<ide> def run
<del> remove_cache_files(*@args)
<add> remove_cache_files(*args)
<ide> end
<ide>
<ide> def cache_files
<ide><path>Library/Homebrew/cask/lib/hbc/cli/edit.rb
<ide> def initialize(*)
<ide>
<ide> def run
<ide> cask_token = args.first
<del> cask_path = CaskLoader.path(cask_token)
<del>
<del> unless cask_path.exist?
<del> raise CaskUnavailableError.new(cask_token, "Run #{Formatter.identifier("brew cask create #{cask_token}")} to create a new Cask.")
<add> cask_path = begin
<add> CaskLoader.load(cask_token).sourcefile_path
<add> rescue CaskUnavailableError => e
<add> reason = e.reason.empty? ? "" : "#{e.reason} "
<add> reason.concat("Run #{Formatter.identifier("brew cask create #{e.token}")} to create a new Cask.")
<add> raise e.class.new(e.token, reason)
<ide> end
<ide>
<ide> odebug "Opening editor for Cask #{cask_token}"
<ide><path>Library/Homebrew/cask/lib/hbc/cli/fetch.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> args.each do |cask_token|
<del> ohai "Downloading external files for Cask #{cask_token}"
<del> cask = CaskLoader.load(cask_token)
<add> raise CaskError, "Fetch incomplete." if fetch_casks == :incomplete
<add> end
<add>
<add> def fetch_casks
<add> casks.each do |cask|
<add> ohai "Downloading external files for Cask #{cask}"
<ide> downloaded_path = Download.new(cask, force: force?).perform
<ide> Verify.all(cask, downloaded_path)
<ide> ohai "Success! Downloaded to -> #{downloaded_path}"
<ide><path>Library/Homebrew/cask/lib/hbc/cli/home.rb
<ide> module Hbc
<ide> class CLI
<ide> class Home < AbstractCommand
<ide> def run
<del> casks = args.map(&CaskLoader.public_method(:load))
<del>
<del> if casks.empty?
<add> if casks.none?
<ide> odebug "Opening project homepage"
<ide> self.class.open_url "https://caskroom.github.io/"
<ide> else
<ide><path>Library/Homebrew/cask/lib/hbc/cli/info.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> args.each do |cask_token|
<del> odebug "Getting info for Cask #{cask_token}"
<del> cask = CaskLoader.load(cask_token)
<del>
<add> casks.each do |cask|
<add> odebug "Getting info for Cask #{cask}"
<ide> self.class.info(cask)
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/cli/install.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> retval = install_casks
<del> # retval is ternary: true/false/nil
<del>
<del> raise CaskError, "nothing to install" if retval.nil?
<del> raise CaskError, "install incomplete" unless retval
<add> raise CaskError, "Install incomplete." if install_casks == :incomplete
<ide> end
<ide>
<ide> def install_casks
<del> count = 0
<del> args.each do |cask_token|
<add> casks.each do |cask|
<ide> begin
<del> cask = CaskLoader.load(cask_token)
<ide> Installer.new(cask, binaries: binaries?,
<del> verbose: verbose?,
<add> verbose: verbose?,
<ide> force: force?,
<ide> skip_cask_deps: skip_cask_deps?,
<ide> require_sha: require_sha?).install
<del> count += 1
<ide> rescue CaskAlreadyInstalledError => e
<ide> opoo e.message
<del> count += 1
<del> rescue CaskUnavailableError => e
<del> self.class.warn_unavailable_with_suggestion cask_token, e
<del> rescue CaskError => e
<del> onoe e.message
<ide> end
<ide> end
<del>
<del> count.zero? ? nil : count == args.length
<del> end
<del>
<del> def self.warn_unavailable_with_suggestion(cask_token, e)
<del> exact_match, partial_matches = Search.search(cask_token)
<del> error_message = e.message
<del> if exact_match
<del> error_message.concat(" Did you mean:\n#{exact_match}")
<del> elsif !partial_matches.empty?
<del> error_message.concat(" Did you mean one of:\n")
<del> .concat(Formatter.columns(partial_matches.take(20)))
<del> end
<del> onoe error_message
<ide> end
<ide>
<ide> def self.help
<ide><path>Library/Homebrew/cask/lib/hbc/cli/internal_dump.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> retval = dump_casks
<del> # retval is ternary: true/false/nil
<del>
<del> raise CaskError, "nothing to dump" if retval.nil?
<del> raise CaskError, "dump incomplete" unless retval
<add> raise CaskError, "Dump incomplete." if dump_casks == :incomplet
<ide> end
<ide>
<ide> def dump_casks
<del> count = 0
<del> args.each do |cask_token|
<del> begin
<del> cask = CaskLoader.load(cask_token)
<del> count += 1
<del> cask.dumpcask
<del> rescue StandardError => e
<del> opoo "#{cask_token} was not found or would not load: #{e}"
<del> end
<del> end
<del> count.zero? ? nil : count == args.length
<add> casks.each(&:dumpcask)
<ide> end
<ide>
<ide> def self.help
<ide><path>Library/Homebrew/cask/lib/hbc/cli/internal_stanza.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> retval = print_stanzas
<del> # retval is ternary: true/false/nil
<del> if retval.nil?
<del> exit 1 if quiet?
<del> raise CaskError, "nothing to print"
<del> elsif !retval
<del> exit 1 if quiet?
<del> raise CaskError, "print incomplete"
<del> end
<add> return unless print_stanzas == :incomplete
<add> exit 1 if quiet?
<add> raise CaskError, "Print incomplete."
<ide> end
<ide>
<ide> def print_stanzas
<del> count = 0
<ide> if ARTIFACTS.include?(stanza)
<ide> artifact_name = stanza
<ide> @stanza = :artifacts
<ide> end
<ide>
<del> cask_tokens = args.empty? ? Hbc.all_tokens : args
<del> cask_tokens.each do |cask_token|
<del> print "#{cask_token}\t" if table?
<del>
<del> begin
<del> cask = CaskLoader.load(cask_token)
<del> rescue StandardError
<del> opoo "Cask '#{cask_token}' was not found" unless quiet?
<del> puts ""
<del> next
<del> end
<add> casks(alternative: -> { Hbc.all }).each do |cask|
<add> print "#{cask}\t" if table?
<ide>
<ide> unless cask.respond_to?(stanza)
<del> opoo "no such stanza '#{stanza}' on Cask '#{cask_token}'" unless quiet?
<add> opoo "no such stanza '#{stanza}' on Cask '#{cask}'" unless quiet?
<ide> puts ""
<ide> next
<ide> end
<ide>
<ide> begin
<ide> value = cask.send(@stanza)
<ide> rescue StandardError
<del> opoo "failure calling '#{stanza}' on Cask '#{cask_token}'" unless quiet?
<add> opoo "failure calling '#{stanza}' on Cask '#{cask}'" unless quiet?
<ide> puts ""
<ide> next
<ide> end
<ide>
<ide> if artifact_name && !value.key?(artifact_name)
<del> opoo "no such stanza '#{artifact_name}' on Cask '#{cask_token}'" unless quiet?
<add> opoo "no such stanza '#{artifact_name}' on Cask '#{cask}'" unless quiet?
<ide> puts ""
<ide> next
<ide> end
<ide> def print_stanzas
<ide> else
<ide> puts value.to_s
<ide> end
<del>
<del> count += 1
<ide> end
<del> count.zero? ? nil : count == cask_tokens.length
<ide> end
<ide>
<ide> def self.help
<ide><path>Library/Homebrew/cask/lib/hbc/cli/list.rb
<ide> class List < AbstractCommand
<ide>
<ide> def run
<ide> retval = args.any? ? list : list_installed
<del> # retval is ternary: true/false/nil
<del> if retval.nil? && args.none?
<del> opoo "nothing to list" # special case: avoid exit code
<del> elsif retval.nil?
<del> raise CaskError, "nothing to list"
<del> elsif !retval
<del> raise CaskError, "listing incomplete"
<del> end
<add> raise CaskError, "Listing incomplete." if retval == :incomplete
<ide> end
<ide>
<ide> def list
<del> count = 0
<del>
<del> args.each do |cask_token|
<del> odebug "Listing files for Cask #{cask_token}"
<del> begin
<del> cask = CaskLoader.load(cask_token)
<add> casks.each do |cask|
<add> raise CaskNotInstalledError, cask unless cask.installed?
<ide>
<del> if cask.installed?
<del> if one?
<del> puts cask.token
<del> elsif versions?
<del> puts self.class.format_versioned(cask)
<del> else
<del> cask = CaskLoader.load_from_file(cask.installed_caskfile)
<del> self.class.list_artifacts(cask)
<del> end
<del>
<del> count += 1
<del> else
<del> opoo "#{cask} is not installed"
<del> end
<del> rescue CaskUnavailableError => e
<del> onoe e
<add> if one?
<add> puts cask.token
<add> elsif versions?
<add> puts self.class.format_versioned(cask)
<add> else
<add> cask = CaskLoader.load_from_file(cask.installed_caskfile)
<add> self.class.list_artifacts(cask)
<ide> end
<ide> end
<del>
<del> count.zero? ? nil : count == args.length
<ide> end
<ide>
<ide> def self.list_artifacts(cask)
<ide> def list_installed
<ide> puts Formatter.columns(installed_casks.map(&:to_s))
<ide> end
<ide>
<del> installed_casks.empty? ? nil : true
<add> installed_casks.empty? ? :empty : :complete
<ide> end
<ide>
<ide> def self.format_versioned(cask)
<ide><path>Library/Homebrew/cask/lib/hbc/cli/outdated.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> casks_to_check = args.empty? ? Hbc.installed : args.map(&CaskLoader.public_method(:load))
<del>
<del> casks_to_check.each do |cask|
<add> casks(alternative: -> { Hbc.installed }).each do |cask|
<ide> odebug "Checking update info of Cask #{cask}"
<ide> self.class.list_if_outdated(cask, greedy?, verbose?)
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/cli/reinstall.rb
<ide> module Hbc
<ide> class CLI
<ide> class Reinstall < Install
<ide> def install_casks
<del> count = 0
<del> args.each do |cask_token|
<del> begin
<del> cask = CaskLoader.load(cask_token)
<del>
<del> Installer.new(cask,
<del> binaries: binaries?,
<del> verbose: verbose?,
<del> force: force?,
<del> skip_cask_deps: skip_cask_deps?,
<del> require_sha: require_sha?).reinstall
<del>
<del> count += 1
<del> rescue CaskUnavailableError => e
<del> self.class.warn_unavailable_with_suggestion cask_token, e
<del> rescue CaskError => e
<del> onoe e.message
<del> end
<add> casks.each do |cask|
<add> Installer.new(cask, binaries: binaries?,
<add> verbose: verbose?,
<add> force: force?,
<add> skip_cask_deps: skip_cask_deps?,
<add> require_sha: require_sha?).reinstall
<ide> end
<del>
<del> count.zero? ? nil : count == args.length
<ide> end
<ide>
<ide> def self.help
<ide><path>Library/Homebrew/cask/lib/hbc/cli/style.rb
<ide> def cask_paths
<ide> elsif args.any? { |file| File.exist?(file) }
<ide> args
<ide> else
<del> args.map { |token| CaskLoader.path(token) }
<add> casks.map(&:sourcefile_path)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/cask/lib/hbc/cli/uninstall.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> args.each do |cask_token|
<del> odebug "Uninstalling Cask #{cask_token}"
<del> cask = CaskLoader.load(cask_token)
<add> raise CaskError, "Uninstall incomplete." if uninstall_casks == :incomplete
<add> end
<add>
<add> def uninstall_casks
<add> casks.each do |cask|
<add> odebug "Uninstalling Cask #{cask}"
<ide>
<ide> raise CaskNotInstalledError, cask unless cask.installed? || force?
<ide>
<ide> def run
<ide> single = versions.count == 1
<ide>
<ide> puts <<-EOS.undent
<del> #{cask_token} #{versions.join(", ")} #{single ? "is" : "are"} still installed.
<del> Remove #{single ? "it" : "them all"} with `brew cask uninstall --force #{cask_token}`.
<add> #{cask} #{versions.join(", ")} #{single ? "is" : "are"} still installed.
<add> Remove #{single ? "it" : "them all"} with `brew cask uninstall --force #{cask}`.
<ide> EOS
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/cli/zap.rb
<ide> def initialize(*)
<ide> end
<ide>
<ide> def run
<del> args.each do |cask_token|
<del> odebug "Zapping Cask #{cask_token}"
<del> cask = CaskLoader.load(cask_token)
<add> raise CaskError, "Zap incomplete." if zap_casks == :incomplete
<add> end
<add>
<add> def zap_casks
<add> casks.each do |cask|
<add> odebug "Zapping Cask #{cask}"
<ide> Installer.new(cask, verbose: verbose?).zap
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/cask/cli/audit_spec.rb
<ide> describe Hbc::CLI::Audit, :cask do
<del> let(:cask) { double }
<add> let(:cask) { double("cask", token: nil) }
<ide>
<ide> describe "selection of Casks to audit" do
<ide> it "audits all Casks if no tokens are given" do
<ide><path>Library/Homebrew/test/cask/cli/cat_spec.rb
<ide> end
<ide>
<ide> it "raises an exception when the Cask does not exist" do
<del> expect {
<del> Hbc::CLI::Cat.run("notacask")
<del> }.to raise_error(Hbc::CaskUnavailableError)
<add> expect { Hbc::CLI::Cat.run("notacask") }
<add> .to output(/is unavailable/).to_stderr
<add> .and raise_error(Hbc::CaskError, "Cat incomplete.")
<ide> end
<ide>
<ide> describe "when no Cask is specified" do
<ide><path>Library/Homebrew/test/cask/cli/fetch_spec.rb
<ide> shutup do
<ide> Hbc::CLI::Fetch.run("notacask")
<ide> end
<del> }.to raise_error(Hbc::CaskUnavailableError)
<add> }.to raise_error(Hbc::CaskError, "Fetch incomplete.")
<ide> end
<ide>
<ide> describe "when no Cask is specified" do
<ide><path>Library/Homebrew/test/cask/cli/install_spec.rb
<ide> shutup do
<ide> Hbc::CLI::Install.run("notacask")
<ide> end
<del> }.to raise_error(Hbc::CaskError)
<add> }.to raise_error(Hbc::CaskError, "Install incomplete.")
<ide> end
<ide>
<ide> it "returns a suggestion for a misspelled Cask" do
<ide> rescue Hbc::CaskError
<ide> nil
<ide> end
<del> }.to output(/Cask 'localcaffeine' is unavailable\. Did you mean:\nlocal-caffeine/).to_stderr
<add> }.to output(/Cask 'localcaffeine' is unavailable: No Cask with this name exists\. Did you mean:\nlocal-caffeine/).to_stderr
<ide> end
<ide>
<ide> it "returns multiple suggestions for a Cask fragment" do
<ide> rescue Hbc::CaskError
<ide> nil
<ide> end
<del> }.to output(/Cask 'local-caf' is unavailable\. Did you mean one of:\nlocal-caffeine/).to_stderr
<add> }.to output(/Cask 'local-caf' is unavailable: No Cask with this name exists\. Did you mean one of:\nlocal-caffeine/).to_stderr
<ide> end
<ide>
<ide> describe "when no Cask is specified" do
<ide><path>Library/Homebrew/test/cask/cli/style_spec.rb
<ide> end
<ide>
<ide> it "tries to find paths for all tokens" do
<del> expect(Hbc::CaskLoader).to receive(:path).twice
<add> expect(Hbc::CaskLoader).to receive(:load).twice.and_return(double("cask", sourcefile_path: nil))
<ide> subject
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/cask/cli/uninstall_spec.rb
<ide> end
<ide>
<ide> it "shows an error when a bad Cask is provided" do
<del> expect {
<del> Hbc::CLI::Uninstall.run("notacask")
<del> }.to raise_error(Hbc::CaskUnavailableError)
<add> expect { Hbc::CLI::Uninstall.run("notacask") }
<add> .to output(/is unavailable/).to_stderr
<add> .and raise_error(Hbc::CaskError, "Uninstall incomplete.")
<ide> end
<ide>
<ide> it "shows an error when a Cask is provided that's not installed" do
<del> expect {
<del> Hbc::CLI::Uninstall.run("local-caffeine")
<del> }.to raise_error(Hbc::CaskNotInstalledError)
<add> expect { Hbc::CLI::Uninstall.run("local-caffeine") }
<add> .to output(/is not installed/).to_stderr
<add> .and raise_error(Hbc::CaskError, "Uninstall incomplete.")
<ide> end
<ide>
<ide> it "tries anyway on a non-present Cask when --force is given" do
<ide>
<ide> Hbc.appdir.join("MyFancyApp.app").rmtree
<ide>
<del> expect {
<del> shutup do
<del> Hbc::CLI::Uninstall.run("with-uninstall-script-app")
<del> end
<del> }.to raise_error(Hbc::CaskError, /does not exist/)
<add> expect { shutup { Hbc::CLI::Uninstall.run("with-uninstall-script-app") } }
<add> .to output(/does not exist/).to_stderr
<add> .and raise_error(Hbc::CaskError, "Uninstall incomplete.")
<ide>
<ide> expect(cask).to be_installed
<ide>
<ide><path>Library/Homebrew/test/cask/cli/zap_spec.rb
<ide> describe Hbc::CLI::Zap, :cask do
<ide> it "shows an error when a bad Cask is provided" do
<del> expect {
<del> Hbc::CLI::Zap.run("notacask")
<del> }.to raise_error(Hbc::CaskUnavailableError)
<add> expect { Hbc::CLI::Zap.run("notacask") }
<add> .to output(/is unavailable/).to_stderr
<add> .and raise_error(Hbc::CaskError, "Zap incomplete.")
<ide> end
<ide>
<ide> it "can zap and unlink multiple Casks at once" do | 24 |
Text | Text | add default colors and secondary button | c759b57edd6917b0316bae1446867a7e7428bffc | <ide><path>guide/english/bootstrap/buttons/index.md
<ide> This is a list of the CSS classes that bootstrap provides for buttons. They give
<ide>
<ide> `<button type="button" class="btn">Basic</button>`
<ide>
<del>`.btn-primary` Bootstrap's primary button.
<add>`.btn-primary` Bootstrap's primary button. Default color displays #007bff.
<ide>
<ide> `<button type="button" class="btn btn-primary">Primary</button>`
<ide>
<del>`.btn-secondary` Bootstrap's secondary button.
<add>`.btn-secondary` Bootstrap's secondary button. Default color displays #6c757d.
<ide>
<ide> `<button type="button" class="btn btn-secondary">Secondary</button>`
<ide>
<del>`.btn-success` Bootstrap's success button.
<add>`.btn-success` Bootstrap's success button. Default color displays #28a745.
<ide>
<ide> `<button type="button" class="btn btn-success">Success</button>`
<ide>
<del>`.btn-info` Bootstrap's info button.
<add>`.btn-info` Bootstrap's info button. Default color displays #17a2b8.
<ide>
<ide> `<button type="button" class="btn btn-info">Info</button>`
<ide>
<del>`.btn-warning` Bootstrap's warning button.
<add>`.btn-warning` Bootstrap's warning button. Default color displays #ffc107.
<ide>
<ide> `<button type="button" class="btn btn-warning">Warning</button>`
<ide>
<del>`.btn-danger` Bootstrap's danger button.
<add>`.btn-danger` Bootstrap's danger button. Default color displays #dc3545.
<ide>
<ide> `<button type="button" class="btn btn-danger">Danger</button>`
<ide> | 1 |
Java | Java | add jni bindings | ca79e6cf30751bd111b95435ea546da3d88f9aab | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatARTSurfaceViewManager.java
<ide> import android.graphics.Bitmap;
<ide>
<ide> import com.facebook.csslayout.CSSMeasureMode;
<del>import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.CSSNodeAPI;
<ide> import com.facebook.csslayout.MeasureOutput;
<ide> import com.facebook.react.uimanager.BaseViewManager;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide>
<ide> private static final String REACT_CLASS = "ARTSurfaceView";
<ide>
<del> private static final CSSNode.MeasureFunction MEASURE_FUNCTION = new CSSNode.MeasureFunction() {
<add> private static final CSSNodeAPI.MeasureFunction MEASURE_FUNCTION = new CSSNodeAPI.MeasureFunction() {
<ide> @Override
<ide> public void measure(
<del> CSSNode node,
<add> CSSNodeAPI node,
<ide> float width,
<ide> CSSMeasureMode widthMode,
<ide> float height,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java
<ide> import android.graphics.Rect;
<ide>
<ide> import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.CSSNodeAPI;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.uimanager.LayoutShadowNode;
<ide> import com.facebook.react.uimanager.OnLayoutEvent;
<ide> protected final void invalidate() {
<ide> }
<ide>
<ide> @Override
<del> protected void markUpdated() {
<add> public void markUpdated() {
<ide> super.markUpdated();
<ide> mIsUpdated = true;
<ide> invalidate();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/NativeViewWrapper.java
<ide> import javax.annotation.Nullable;
<ide>
<ide> import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.CSSNodeAPI;
<ide> import com.facebook.react.uimanager.ReactStylesDiffMap;
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide>
<ide> /* package */ NativeViewWrapper(ViewManager viewManager) {
<ide> ReactShadowNode reactShadowNode = viewManager.createShadowNodeInstance();
<del> if (reactShadowNode instanceof CSSNode.MeasureFunction) {
<add> if (reactShadowNode instanceof CSSNodeAPI.MeasureFunction) {
<ide> mReactShadowNode = reactShadowNode;
<del> setMeasureFunction((CSSNode.MeasureFunction) reactShadowNode);
<add> setMeasureFunction((CSSNodeAPI.MeasureFunction) reactShadowNode);
<ide> } else {
<ide> mReactShadowNode = null;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTText.java
<ide> import android.text.TextUtils;
<ide>
<ide> import com.facebook.csslayout.CSSMeasureMode;
<del>import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.CSSNodeAPI;
<ide> import com.facebook.csslayout.MeasureOutput;
<ide> import com.facebook.csslayout.Spacing;
<ide> import com.facebook.fbui.widget.text.layoutbuilder.TextLayoutBuilder;
<ide> * a) RCTText is not a virtual node, and can be measured and laid out.
<ide> * b) when no font size is specified, a font size of ViewDefaults#FONT_SIZE_SP is assumed.
<ide> */
<del>/* package */ final class RCTText extends RCTVirtualText implements CSSNode.MeasureFunction {
<add>/* package */ final class RCTText extends RCTVirtualText implements CSSNodeAPI.MeasureFunction {
<ide>
<ide> // We set every value we use every time we use the layout builder, so we can get away with only
<ide> // using a single instance.
<ide> public boolean isVirtualAnchor() {
<ide>
<ide> @Override
<ide> public void measure(
<del> CSSNode node,
<add> CSSNodeAPI node,
<ide> float width,
<ide> CSSMeasureMode widthMode,
<ide> float height,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTTextInput.java
<ide> import android.widget.EditText;
<ide>
<ide> import com.facebook.csslayout.CSSMeasureMode;
<del>import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.CSSNodeAPI;
<ide> import com.facebook.csslayout.MeasureOutput;
<ide> import com.facebook.csslayout.Spacing;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import static com.facebook.react.views.text.ReactTextShadowNode.PROP_TEXT;
<ide> import static com.facebook.react.views.text.ReactTextShadowNode.UNSET;
<ide>
<del>public class RCTTextInput extends RCTVirtualText implements AndroidView, CSSNode.MeasureFunction {
<add>public class RCTTextInput extends RCTVirtualText implements AndroidView, CSSNodeAPI.MeasureFunction {
<ide>
<ide> @Nullable private String mText;
<ide> private int mJsEventCount = UNSET;
<ide> public void setThemedContext(ThemedReactContext themedContext) {
<ide>
<ide> @Override
<ide> public void measure(
<del> CSSNode node,
<add> CSSNodeAPI node,
<ide> float width,
<ide> CSSMeasureMode widthMode,
<ide> float height, | 5 |
Javascript | Javascript | fix _debugger by properly proxying repl | 051d482b151cc15b8273d705ec57209d0fa1db2a | <ide><path>lib/internal/repl.js
<ide> 'use strict';
<ide>
<del>module.exports = {createRepl: createRepl};
<del>
<ide> const Interface = require('readline').Interface;
<ide> const REPL = require('repl');
<ide> const path = require('path');
<ide>
<add>module.exports = Object.create(REPL);
<add>module.exports.createInternalRepl = createRepl;
<add>
<ide> // XXX(chrisdickinson): The 15ms debounce value is somewhat arbitrary.
<ide> // The debounce is to guard against code pasted into the REPL.
<ide> const kDebounceHistoryMS = 15;
<ide>
<del>try {
<del> // hack for require.resolve("./relative") to work properly.
<del> module.filename = path.resolve('repl');
<del>} catch (e) {
<del> // path.resolve('repl') fails when the current working directory has been
<del> // deleted. Fall back to the directory name of the (absolute) executable
<del> // path. It's not really correct but what are the alternatives?
<del> const dirname = path.dirname(process.execPath);
<del> module.filename = path.resolve(dirname, 'repl');
<add>// XXX(chrisdickinson): hack to make sure that the internal debugger
<add>// uses the original repl.
<add>function replStart() {
<add> return REPL.start.apply(REPL, arguments);
<ide> }
<ide>
<del>// hack for repl require to work properly with node_modules folders
<del>module.paths = require('module')._nodeModulePaths(module.filename);
<del>
<ide> function createRepl(env, cb) {
<ide> const opts = {
<ide> ignoreUndefined: false,
<ide><path>lib/repl.js
<ide> const Console = require('console').Console;
<ide> const domain = require('domain');
<ide> const debug = util.debuglog('repl');
<ide>
<add>try {
<add> // hack for require.resolve("./relative") to work properly.
<add> module.filename = path.resolve('repl');
<add>} catch (e) {
<add> // path.resolve('repl') fails when the current working directory has been
<add> // deleted. Fall back to the directory name of the (absolute) executable
<add> // path. It's not really correct but what are the alternatives?
<add> const dirname = path.dirname(process.execPath);
<add> module.filename = path.resolve(dirname, 'repl');
<add>}
<add>
<add>// hack for repl require to work properly with node_modules folders
<add>module.paths = require('module')._nodeModulePaths(module.filename);
<add>
<ide> // If obj.hasOwnProperty has been overridden, then calling
<ide> // obj.hasOwnProperty(prop) will break.
<ide> // See: https://github.com/joyent/node/issues/1707
<ide><path>src/node.js
<ide> // If -i or --interactive were passed, or stdin is a TTY.
<ide> if (process._forceRepl || NativeModule.require('tty').isatty(0)) {
<ide> // REPL
<del> Module.requireRepl().createRepl(process.env, function(err, repl) {
<add> Module.requireRepl().createInternalRepl(process.env, function(err, repl) {
<ide> if (err) {
<ide> throw err;
<ide> } | 3 |
PHP | PHP | batch() doc block | f857dd2248df3b909cb7dd0bd47c9117f8a38a39 | <ide><path>src/Illuminate/Bus/Dispatcher.php
<ide> public function findBatch(string $batchId)
<ide> /**
<ide> * Create a new batch of queueable jobs.
<ide> *
<del> * @param \Illuminate\Support\Collection|array $jobs
<add> * @param \Illuminate\Support\Collection|array|mixed $jobs
<ide> * @return \Illuminate\Bus\PendingBatch
<ide> */
<ide> public function batch($jobs)
<ide><path>src/Illuminate/Support/Facades/Bus.php
<ide>
<ide> /**
<ide> * @method static \Illuminate\Bus\Batch|null findBatch(string $batchId)
<del> * @method static \Illuminate\Bus\PendingBatch batch(array $jobs)
<add> * @method static \Illuminate\Bus\PendingBatch batch(array|mixed $jobs)
<ide> * @method static \Illuminate\Contracts\Bus\Dispatcher map(array $map)
<ide> * @method static \Illuminate\Contracts\Bus\Dispatcher pipeThrough(array $pipes)
<ide> * @method static \Illuminate\Foundation\Bus\PendingChain chain(array $jobs) | 2 |
Ruby | Ruby | use start_with? instead of regexp | d494c9db8e24740d87c0717ed35ca8731f7e209b | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_config_scripts
<ide>
<ide> paths.each do |p|
<ide> next if whitelist.include? p.downcase
<del> next if p =~ %r[^(#{real_cellar.to_s}|#{HOMEBREW_CELLAR.to_s})]
<add> next if p.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s)
<ide>
<ide> configs = Dir["#{p}/*-config"]
<ide> config_scripts << [p, configs.map { |c| File.basename(c) }] unless configs.empty? | 1 |
PHP | PHP | use correct typehint | 3c874bc92fa13b6542387f58058cf216f934ccfb | <ide><path>src/Controller/Component/AuthComponent.php
<ide> protected function _isLoginAction(Controller $controller): bool
<ide> * Handle unauthorized access attempt
<ide> *
<ide> * @param \Cake\Controller\Controller $controller A reference to the controller object
<del> * @return \Cake\Http\Response
<add> * @return \Cake\Http\Response|null
<ide> * @throws \Cake\Http\Exception\ForbiddenException
<ide> */
<del> protected function _unauthorized(Controller $controller): Response
<add> protected function _unauthorized(Controller $controller): ?Response
<ide> {
<ide> if ($this->_config['unauthorizedRedirect'] === false) {
<ide> throw new ForbiddenException($this->_config['authError']); | 1 |
Python | Python | fix broken xcom in ekspodoperator | 653c13ec0cf4729f991adf8c7b37b3a272caac56 | <ide><path>airflow/providers/amazon/aws/operators/eks.py
<ide> def execute(self, context):
<ide> pod_username=self.pod_username,
<ide> pod_context=self.pod_context,
<ide> ) as self.config_file:
<del> super().execute(context)
<add> return super().execute(context) | 1 |
Javascript | Javascript | remove redundant msie variable | 6cba9c5e7c22dcedb585c16719f081d5fddeccaf | <ide><path>src/ngScenario/browserTrigger.js
<ide> 'use strict';
<ide>
<ide> (function() {
<del> /**
<del> * documentMode is an IE-only property
<del> * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
<del> */
<del> var msie = document.documentMode;
<del>
<ide> /**
<ide> * Triggers a browser event. Attempts to choose the right event if one is
<ide> * not specified. | 1 |
PHP | PHP | add default mask for sqlite database | 3cce61360bc513808973b9ed4b278e7ec1aad1cb | <ide><path>src/Database/Driver/Sqlite.php
<ide> class Sqlite extends Driver
<ide> 'password' => null,
<ide> 'database' => ':memory:',
<ide> 'encoding' => 'utf8',
<add> 'mask' => 0644,
<ide> 'flags' => [],
<ide> 'init' => [],
<ide> ]; | 1 |
Text | Text | convert tabs to spaces | 9ddc915a9ccb64a786fdf90fb6ffc2a8792c74a8 | <ide><path>doc/changelogs/CHANGELOG_ARCHIVE.md
<ide> https://github.com/nodejs/node/commit/8b8a7a7f9b41e74e1e810d0330738ad06fc302ec
<ide> https://github.com/nodejs/node/commit/a72120190a8ffdbcd3d6ad2a2e6ceecd2087111e
<ide>
<ide> * npm: Upgrade to 1.1.30
<del> - Improved 'npm init'
<del> - Fix the 'cb never called' error from 'oudated' and 'update'
<del> - Add --save-bundle|-B config
<del> - Fix isaacs/npm[#2465](https://github.com/joyent/node/issues/2465): Make npm script and windows shims cygwin-aware
<del> - Fix isaacs/npm[#2452](https://github.com/joyent/node/issues/2452) Use --save(-dev|-optional) in npm rm
<del> - `logstream` option to replace removed `logfd` (Rod Vagg)
<del> - Read default descriptions from README.md files
<add> - Improved 'npm init'
<add> - Fix the 'cb never called' error from 'oudated' and 'update'
<add> - Add --save-bundle|-B config
<add> - Fix isaacs/npm[#2465](https://github.com/joyent/node/issues/2465): Make npm script and windows shims cygwin-aware
<add> - Fix isaacs/npm[#2452](https://github.com/joyent/node/issues/2452) Use --save(-dev|-optional) in npm rm
<add> - `logstream` option to replace removed `logfd` (Rod Vagg)
<add> - Read default descriptions from README.md files
<ide>
<ide> * Shims to support deprecated ev_* and eio_* methods (Ben Noordhuis)
<ide> * [#3118](https://github.com/joyent/node/issues/3118) net.Socket: Delay pause/resume until after connect (isaacs)
<ide> https://github.com/nodejs/node/commit/12a32a48a30182621b3f8e9b9695d1946b53c131
<ide> * child_process: new stdio API for .spawn() method (Fedor Indutny)
<ide> * child_process: spawn().ref() and spawn().unref() (Fedor Indutny)
<ide> * Upgrade npm to 1.1.25
<del> - Enable npm link on windows
<del> - Properly remove sh-shim on Windows
<del> - Abstract out registry client and logger
<add> - Enable npm link on windows
<add> - Properly remove sh-shim on Windows
<add> - Abstract out registry client and logger
<ide>
<ide> <a id="0.7.9"></a>
<ide> ## 2012.05.28, Version 0.7.9 (unstable)
<ide> https://github.com/nodejs/node/commit/865b077819a9271a29f982faaef99dc635b57fbc
<ide> https://github.com/nodejs/node/commit/220e61c1f65bf4db09699fcf6399c0809c0bc446
<ide>
<ide> * Remove cmake build system, support for Cygwin, legacy code base,
<del> process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle
<add> process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle
<ide>
<ide> * Documentation improvements (Igor Zinkovsky, Bert Belder, Ilya Dmitrichenko,
<ide> koichik, Maciej Małecki, Guglielmo Ferri, isaacs)
<ide> https://github.com/nodejs/node/commit/4585330afef44ddfb6a4054bd9b0f190b352628b
<ide> * Add support for TLS SNI (Fedor Indutny)
<ide> * New http agent implementation. Off by default the command line flag
<ide> --use-http2 will enable it. "make test-http2" will run the tests
<del> for the new implementation. (Mikeal Rogers)
<add> for the new implementation. (Mikeal Rogers)
<ide>
<ide> * Revert AMD compatibility. (isaacs)
<ide> * Windows: improvements, child_process support.
<ide> https://github.com/nodejs/node/commit/7dd22c26e4365698dc3efddf138c4d399cb912c8
<ide> * [#983](https://github.com/joyent/node/issues/983) Better JSON.parse error detection in REPL (isaacs)
<ide> * [#836](https://github.com/joyent/node/issues/836) Agent socket errors bubble up to req only if req exists
<ide> * [#1041](https://github.com/joyent/node/issues/1041) Fix event listener leak check timing (koichik)
<del>* [#1038](https://github.com/joyent/node/issues/1038) Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR"
<add>* [#1038](https://github.com/joyent/node/issues/1038) Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR"
<ide> (koichik)
<ide>
<ide> * [#1073](https://github.com/joyent/node/issues/1073) Share SSL context between server connections (Fedor Indutny)
<ide> https://github.com/nodejs/node/commit/7dd22c26e4365698dc3efddf138c4d399cb912c8
<ide>
<ide> * Doc improvements
<ide> * cleartextstream.destroy() should close(2) the socket. Previously was being
<del> mapped to a shutdown(2) syscall.
<add> mapped to a shutdown(2) syscall.
<ide>
<ide> * No longer compile out asserts and debug statements in normal build.
<ide> * Debugger improvements.
<ide> https://github.com/nodejs/node/commit/58002d56bc79410c5ff397fc0e1ffec0665db38a
<ide>
<ide> * Don't error on ENOTCONN from shutdown() [#670](https://github.com/joyent/node/issues/670)
<ide> * Auto completion of built-in debugger suggests prefix match rather than
<del> partial match. (koichik)
<add> partial match. (koichik)
<ide>
<ide> * circular reference in vm modules. [#822](https://github.com/joyent/node/issues/822) (Jakub Lekstan)
<ide> * http response.readable should be false after 'end' [#867](https://github.com/joyent/node/issues/867) (Abe Fettig)
<ide> * Implement os.cpus() and os.uptime() on Solaris (Scott McWhirter)
<ide> * fs.ReadStream: Allow omission of end option for range reads [#801](https://github.com/joyent/node/issues/801)
<del> (Felix Geisendörfer)
<add> (Felix Geisendörfer)
<ide>
<ide> * Buffer.write() with UCS-2 should not be write partial char
<del> [#916](https://github.com/joyent/node/issues/916) (koichik)
<add> [#916](https://github.com/joyent/node/issues/916) (koichik)
<ide>
<ide> * Pass secureProtocol through on tls.Server creation (Theo Schlossnagle)
<ide> * TLS use RC4-SHA by default
<ide> https://github.com/nodejs/node/commit/25122b986a90ba0982697b7abcb0158c302a1019
<ide> https://github.com/nodejs/node/commit/c095ce1a1b41ca015758a713283bf1f0bd41e4c4
<ide>
<ide> * Don't decrease server connection counter again if destroy() is called more
<del> than once GH-431 (Andreas Reich, Anders Conbere)
<add> than once GH-431 (Andreas Reich, Anders Conbere)
<ide>
<ide> * Documentation improvements (koichik)
<ide> * Fix bug with setMaxListeners GH-682
<ide> https://github.com/nodejs/node/commit/b14dd49222687c12f3e8eac597cff4f2674f84e8
<ide> * Set cwd for child processes (Bert Belder)
<ide> * Tab completion for readline (Trent Mick)
<ide> * process.title getter/setter for OSX, Linux, Cygwin.
<del> (Rasmus Andersson, Bert Belder)
<add> (Rasmus Andersson, Bert Belder)
<ide>
<ide> * Upgrade V8 to 2.3.6
<ide>
<ide><path>doc/changelogs/CHANGELOG_V010.md
<ide> https://github.com/nodejs/node/commit/8d045a30e95602b443eb259a5021d33feb4df079
<ide> * uv: Update to v0.10.29
<ide> * child_process: properly support optional args (cjihrig)
<ide> * crypto: Disable autonegotiation for SSLv2/3 by default (Fedor Indutny,
<del> Timothy J Fontaine, Alexis Campailla)
<del> This is a behavior change, by default we will not allow the negotiation to
<del> SSLv2 or SSLv3. If you want this behavior, run Node.js with either
<del> `--enable-ssl2` or `--enable-ssl3` respectively.
<del> This does not change the behavior for users specifically requesting
<del> `SSLv2_method` or `SSLv3_method`. While this behavior is not advised, it is
<del> assumed you know what you're doing since you're specifically asking to use
<del> these methods.
<add> Timothy J Fontaine, Alexis Campailla)
<add> This is a behavior change, by default we will not allow the negotiation to
<add> SSLv2 or SSLv3. If you want this behavior, run Node.js with either
<add> `--enable-ssl2` or `--enable-ssl3` respectively.
<add> This does not change the behavior for users specifically requesting
<add> `SSLv2_method` or `SSLv3_method`. While this behavior is not advised, it is
<add> assumed you know what you're doing since you're specifically asking to use
<add> these methods.
<ide>
<ide> <a id="0.10.32"></a>
<ide> ## 2014.09.16, Version 0.10.32 (Stable)
<ide><path>doc/ctc-meetings/2016-06-15.md
<ide> Extracted from **ctc-agenda** labelled issues and pull requests from the **nodej
<ide> * Keeping up with issues
<ide>
<ide> * Brian White @mscdex (CTC)
<del> * Landed some old PRs
<add> * Landed some old PRs
<ide> * Submitting PRs to fix some regressions
<ide> * Reviewed PRs and issues
<ide> | 3 |
Go | Go | add cmdlogs test | 177a2f5946623a4d4f90f5a227e57211eed6ade3 | <ide><path>commands_test.go
<ide> func TestRunAutoRemove(t *testing.T) {
<ide> t.Fatalf("failed to remove container automatically: container %s still exists", temporaryContainerID)
<ide> }
<ide> }
<add>
<add>func TestCmdLogs(t *testing.T) {
<add> cli := NewDockerCli(nil, ioutil.Discard, ioutil.Discard, testDaemonProto, testDaemonAddr)
<add> defer cleanup(globalRuntime)
<add>
<add> if err := cli.CmdRun(unitTestImageID, "sh", "-c", "ls -l"); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := cli.CmdRun("-t", unitTestImageID, "sh", "-c", "ls -l"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := cli.CmdLogs(globalRuntime.List()[0].ID); err != nil {
<add> t.Fatal(err)
<add> }
<add>} | 1 |
Javascript | Javascript | use jquery again in e2e tests | feed7d694441419b99e876188c36aeff1ae05090 | <ide><path>docs/gulpfile.js
<ide> gulp.task('assets', ['bower'], function() {
<ide> copyComponent('open-sans-fontface'),
<ide> copyComponent('lunr.js','/*.js'),
<ide> copyComponent('google-code-prettify'),
<del> copyComponent('jquery', '/jquery.*'),
<add> copyComponent('jquery', '/dist/*.js'),
<ide> copyComponent('marked', '/**/*.js', '../node_modules', 'package.json')
<ide> );
<ide> }); | 1 |
Javascript | Javascript | fix dimensions for componentscript | 103ec2f770dbb785ef4bc26f8662c74edded796a | <ide><path>Libraries/Utilities/Dimensions.js
<ide> class Dimensions {
<ide> }
<ide> }
<ide>
<del>// Subscribe before calling getConstants to make sure we don't miss any updates in between.
<del>RCTDeviceEventEmitter.addListener(
<del> 'didUpdateDimensions',
<del> (update: DimensionsPayload) => {
<del> Dimensions.set(update);
<del> },
<del>);
<del>Dimensions.set(NativeDeviceInfo.getConstants().Dimensions);
<add>let initialDims: ?$ReadOnly<{[key: string]: any}> =
<add> global.nativeExtensions &&
<add> global.nativeExtensions.DeviceInfo &&
<add> global.nativeExtensions.DeviceInfo.Dimensions;
<add>if (!initialDims) {
<add> // Subscribe before calling getConstants to make sure we don't miss any updates in between.
<add> RCTDeviceEventEmitter.addListener(
<add> 'didUpdateDimensions',
<add> (update: DimensionsPayload) => {
<add> Dimensions.set(update);
<add> },
<add> );
<add> // Can't use NativeDeviceInfo in ComponentScript because it does not support NativeModules,
<add> // but has nativeExtensions instead.
<add> initialDims = NativeDeviceInfo.getConstants().Dimensions;
<add>}
<add>
<add>Dimensions.set(initialDims);
<ide>
<ide> module.exports = Dimensions; | 1 |
Javascript | Javascript | avoid bool conversion | 974155e35d23785a6ddcd0a4a2f131a41c7cffd5 | <ide><path>packages/ember-metal/lib/property_events.js
<ide> function propertyWillChange(obj, keyName, _meta) {
<ide>
<ide> let watching = meta && meta.peekWatching(keyName) > 0;
<ide> let possibleDesc = obj[keyName];
<del> let desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
<add> let isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<ide>
<del> if (desc && desc.willChange) {
<del> desc.willChange(obj, keyName);
<add> if (isDescriptor && possibleDesc.willChange) {
<add> possibleDesc.willChange(obj, keyName);
<ide> }
<ide>
<ide> if (watching) {
<ide> function propertyDidChange(obj, keyName, _meta) {
<ide> }
<ide>
<ide> let possibleDesc = obj[keyName];
<del> let desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
<add> let isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<ide>
<ide> // shouldn't this mean that we're watching this key?
<del> if (desc && desc.didChange) {
<del> desc.didChange(obj, keyName);
<add> if (isDescriptor && possibleDesc.didChange) {
<add> possibleDesc.didChange(obj, keyName);
<ide> }
<ide>
<ide> if (hasMeta && meta.peekWatching(keyName) > 0) {
<ide> function dependentKeysDidChange(obj, depKey, meta) {
<ide> }
<ide>
<ide> function iterDeps(method, obj, depKey, seen, meta) {
<del> let possibleDesc, desc;
<add> let possibleDesc, isDescriptor;
<ide> let guid = guidFor(obj);
<ide> let current = seen[guid];
<ide>
<ide> function iterDeps(method, obj, depKey, seen, meta) {
<ide> if (!value) { return; }
<ide>
<ide> possibleDesc = obj[key];
<del> desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
<add> isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<ide>
<del> if (desc && desc._suspended === obj) {
<add> if (isDescriptor && possibleDesc._suspended === obj) {
<ide> return;
<ide> }
<ide>
<ide><path>packages/ember-metal/lib/watch_key.js
<ide> export function watchKey(obj, keyName, meta) {
<ide> m.writeWatching(keyName, 1);
<ide>
<ide> let possibleDesc = obj[keyName];
<del> let desc = (possibleDesc !== null &&
<del> typeof possibleDesc === 'object' &&
<del> possibleDesc.isDescriptor) ? possibleDesc : undefined;
<del> if (desc && desc.willWatch) { desc.willWatch(obj, keyName); }
<add> let isDescriptor = possibleDesc !== null &&
<add> typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<add> if (isDescriptor && possibleDesc.willWatch) { possibleDesc.willWatch(obj, keyName); }
<ide>
<ide> if ('function' === typeof obj.willWatchProperty) {
<ide> obj.willWatchProperty(keyName);
<ide> export function unwatchKey(obj, keyName, _meta) {
<ide> meta.writeWatching(keyName, 0);
<ide>
<ide> let possibleDesc = obj[keyName];
<del> let desc = (possibleDesc !== null &&
<del> typeof possibleDesc === 'object' &&
<del> possibleDesc.isDescriptor) ? possibleDesc : undefined;
<add> let isDescriptor = possibleDesc !== null &&
<add> typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<ide>
<del> if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); }
<add> if (isDescriptor && possibleDesc.didUnwatch) { possibleDesc.didUnwatch(obj, keyName); }
<ide>
<ide> if ('function' === typeof obj.didUnwatchProperty) {
<ide> obj.didUnwatchProperty(keyName);
<ide> export function unwatchKey(obj, keyName, _meta) {
<ide> // for mutation, will bypass observation. This code exists to assert when
<ide> // that occurs, and attempt to provide more helpful feedback. The alternative
<ide> // is tricky to debug partially observable properties.
<del> if (!desc && keyName in obj) {
<add> if (!isDescriptor && keyName in obj) {
<ide> let maybeMandatoryDescriptor = lookupDescriptor(obj, keyName);
<ide>
<ide> if (maybeMandatoryDescriptor.set && maybeMandatoryDescriptor.set.isMandatorySetter) {
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> function makeCtor() {
<ide> m.writeBindings(keyName, value);
<ide> }
<ide>
<del> let possibleDesc = this[keyName];
<del> let desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
<del>
<ide> assert(
<ide> 'Ember.Object.create no longer supports defining computed ' +
<ide> 'properties. Define computed properties using extend() or reopen() ' +
<ide> function makeCtor() {
<ide> value = assign({}, originalValue, value);
<ide> }
<ide>
<del> if (desc) {
<del> desc.set(this, keyName, value);
<add> let possibleDesc = this[keyName];
<add> let isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
<add>
<add> if (isDescriptor) {
<add> possibleDesc.set(this, keyName, value);
<ide> } else {
<ide> if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
<ide> this.setUnknownProperty(keyName, value); | 3 |
Go | Go | remove the os check when creating a container | 1a3d8019d1ddb82e8a6b437a8eccf2d22cbc8b5d | <ide><path>daemon/create.go
<ide> import (
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/idtools"
<del> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/runconfig"
<ide> v1 "github.com/opencontainers/image-spec/specs-go/v1"
<ide> "github.com/opencontainers/selinux/go-selinux"
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide> return nil, err
<ide> }
<ide> os = img.OperatingSystem()
<del> if !system.IsOSSupported(os) {
<del> return nil, system.ErrNotSupportedOperatingSystem
<del> }
<ide> imgID = img.ID()
<ide> } else if isWindows {
<ide> os = "linux" // 'scratch' case. | 1 |
PHP | PHP | add backwards compatibility mode for get() | 9860a554ae5fd9250bf7a1392618c78b59f78037 | <ide><path>src/Http/Cookie/CookieCollection.php
<ide> public function add(CookieInterface $cookie)
<ide> /**
<ide> * Get the first cookie by name.
<ide> *
<del> * If the provided name matches a URL (matches `#^https?://#`) this method
<add> * If the provided name matches a URL (starts with `http:`) this method
<ide> * will assume you want a list of cookies that match that URL. This is
<ide> * backwards compatible behavior that will be removed in 4.0.0
<ide> *
<ide> public function add(CookieInterface $cookie)
<ide> */
<ide> public function get($name)
<ide> {
<add> if (substr($name, 0, 4) === 'http') {
<add> return $this->getByUrl($name);
<add> }
<ide> $key = mb_strtolower($name);
<ide> foreach ($this->cookies as $cookie) {
<ide> if (mb_strtolower($cookie->getName()) === $key) {
<ide> public function get($name)
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Backwards compatibility helper for consumers of Client\CookieCollection
<add> *
<add> * @param string $url The url to get cookies for.
<add> * @return array An array of matching cookies.
<add> * @deprecated 3.5.0 Will be removed in 4.0.0. Use addToRequest() instead.
<add> */
<add> protected function getByUrl($url)
<add> {
<add> $path = parse_url($url, PHP_URL_PATH) ?: '/';
<add> $host = parse_url($url, PHP_URL_HOST);
<add> $scheme = parse_url($url, PHP_URL_SCHEME);
<add>
<add> return $this->findMatchingCookies($scheme, $host, $path);
<add> }
<add>
<ide> /**
<ide> * Check if a cookie with the given name exists
<ide> *
<ide> public function addToRequest(RequestInterface $request)
<ide> $path = $uri->getPath();
<ide> $host = $uri->getHost();
<ide> $scheme = $uri->getScheme();
<add> $cookies = $this->findMatchingCookies($scheme, $host, $path);
<add> $cookies = array_merge($request->getCookieParams(), $cookies);
<ide>
<add> return $request->withCookieParams($cookies);
<add> }
<add>
<add> /**
<add> * Find cookies matching the scheme, host, and path
<add> *
<add> * @param string $scheme The http scheme to match
<add> * @param string $host The host to match.
<add> * @param string $path The path to match
<add> * @return array An array of cookie name/value pairs
<add> */
<add> protected function findMatchingCookies($scheme, $host, $path)
<add> {
<ide> $out = [];
<ide> foreach ($this->cookies as $cookie) {
<ide> if ($scheme === 'http' && $cookie->isSecure()) {
<ide> public function addToRequest(RequestInterface $request)
<ide> $domain = ltrim($domain, '.');
<ide> }
<ide>
<del> if ($cookie->getExpiry() && time() > $cookie->getExpiry()) {
<add> $expires = $cookie->getExpiry();
<add> if ($expires && time() > $expires) {
<ide> continue;
<ide> }
<ide>
<ide> public function addToRequest(RequestInterface $request)
<ide>
<ide> $out[$cookie->getName()] = $cookie->getValue();
<ide> }
<del> $cookies = array_merge($request->getCookieParams(), $out);
<ide>
<del> return $request->withCookieParams($cookies);
<add> return $out;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> public function testGetByName()
<ide> $this->assertSame($cookies[0], $collection->get('remember_me'));
<ide> }
<ide>
<add> /**
<add> * Test that get() provides backwards compat behavior.
<add> *
<add> * When the parameter is a string that looks like a URL
<add> *
<add> * @return void
<add> */
<add> public function testGetBackwardsCompatibility()
<add> {
<add> $cookies = [
<add> new Cookie('test', 'value', null, '/api', 'example.com', true),
<add> new Cookie('test_two', 'value2', null, '/blog', 'blog.example.com', true),
<add> new Cookie('test3', 'value3', null, '/blog', 'blog.example.com', false),
<add> ];
<add> $collection = new CookieCollection($cookies);
<add> $result = $collection->get('http://example.com/api');
<add> $this->assertSame([], $result);
<add>
<add> $result = $collection->get('https://example.com/api');
<add> $this->assertSame(['test' => 'value'], $result);
<add>
<add> $result = $collection->get('http://foo.blog.example.com/blog/path');
<add> $this->assertSame(['test3' => 'value3'], $result);
<add>
<add> $result = $collection->get('https://foo.blog.example.com/blog/path');
<add> $this->assertSame(['test_two' => 'value2', 'test3' => 'value3'], $result);
<add> }
<add>
<ide> /**
<ide> * Test that the constructor takes only an array of objects implementing
<ide> * the CookieInterface
<ide> public function testStoreCompatibility()
<ide> $this->assertFalse($collection->has('expired'));
<ide> }
<ide>
<del> /**
<del> * Test that get() provides backwards compat behavior.
<del> *
<del> * When the parameter is a string that looks like a URL
<del> *
<del> * @return void
<del> */
<del> public function testGetBackwardsCompatibility()
<del> {
<del> $this->markTestIncomplete();
<del> }
<del>
<ide> /**
<ide> * Test that getAll() provides backwards compat behavior.
<ide> * | 2 |
Python | Python | improve performance for noncallble attributes | 281fc074ba255ed9c5724cc971fa86c78d4dca38 | <ide><path>rest_framework/fields.py
<ide> def is_simple_callable(obj):
<ide> """
<ide> True if the object is a callable that takes no arguments.
<ide> """
<add> if not callable(obj):
<add> return False
<add>
<ide> # Bail early since we cannot inspect built-in function signatures.
<ide> if inspect.isbuiltin(obj):
<ide> raise BuiltinSignatureError(
<ide><path>tests/test_fields.py
<ide> def invalid(param, param2='value'):
<ide> assert is_simple_callable(valid_vargs_kwargs)
<ide> assert not is_simple_callable(invalid)
<ide>
<add> @pytest.mark.parametrize('obj', (True, None, "str", b'bytes', 123, 1.23))
<add> def test_not_callable(self, obj):
<add> assert not is_simple_callable(obj)
<add>
<ide> def test_4602_regression(self):
<ide> from django.db import models
<ide> | 2 |
Python | Python | fix a regression introduced by f011b90363 | fed2877cf1307eb9c3ef36787fe96a51526db17e | <ide><path>django/core/management/__init__.py
<ide> def execute(self):
<ide> # These options could affect the commands that are available, so they
<ide> # must be processed early.
<ide> parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
<del> version=get_version(),
<add> version=django.get_version(),
<ide> option_list=BaseCommand.option_list)
<ide> try:
<ide> options, args = parser.parse_args(self.argv) | 1 |
Ruby | Ruby | remove delegation to `chain` | 4bf10fcdee37ca4f16e04e26b7720568b14b0e4b | <ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb
<ide> class JoinAssociation < JoinPart # :nodoc:
<ide>
<ide> attr_accessor :tables
<ide>
<del> delegate :chain, :to => :reflection
<del>
<ide> def initialize(reflection, index, join_type)
<ide> super(reflection.klass)
<ide>
<ide> def join_constraints(parent, tables)
<ide>
<ide> # The chain starts with the target table, but we want to end with it here (makes
<ide> # more sense in this context), so we reverse
<del> chain.reverse_each do |reflection|
<add> reflection.chain.reverse_each do |reflection|
<ide> table = tables.shift
<ide> klass = reflection.klass
<ide> | 1 |
Go | Go | remove attachable network on swarm leave | 3cedca5d532958ffc007d9b62cc871d3d113f054 | <ide><path>daemon/cluster/cluster.go
<ide> func (c *Cluster) newNodeRunner(conf nodeStartConfig) (*nodeRunner, error) {
<ide> return nil, err
<ide> }
<ide>
<del> c.config.Backend.SetClusterProvider(c)
<add> c.config.Backend.DaemonJoinsCluster(c)
<ide>
<ide> return nr, nil
<ide> }
<ide> func (c *Cluster) Leave(force bool) error {
<ide> if err := clearPersistentState(c.root); err != nil {
<ide> return err
<ide> }
<del> c.config.Backend.SetClusterProvider(nil)
<add> c.config.Backend.DaemonLeavesCluster()
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/cluster/executor/backend.go
<ide> type Backend interface {
<ide> VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error)
<ide> Containers(config *types.ContainerListOptions) ([]*types.Container, error)
<ide> SetNetworkBootstrapKeys([]*networktypes.EncryptionKey) error
<del> SetClusterProvider(provider cluster.Provider)
<add> DaemonJoinsCluster(provider cluster.Provider)
<add> DaemonLeavesCluster()
<ide> IsSwarmCompatible() error
<ide> SubscribeToEvents(since, until time.Time, filter filters.Args) ([]events.Message, chan interface{})
<ide> UnsubscribeFromEvents(listener chan interface{})
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) registerLink(parent, child *container.Container, alias str
<ide> return nil
<ide> }
<ide>
<del>// SetClusterProvider sets a component for querying the current cluster state.
<del>func (daemon *Daemon) SetClusterProvider(clusterProvider cluster.Provider) {
<add>// DaemonJoinsCluster informs the daemon has joined the cluster and provides
<add>// the handler to query the cluster component
<add>func (daemon *Daemon) DaemonJoinsCluster(clusterProvider cluster.Provider) {
<add> daemon.setClusterProvider(clusterProvider)
<add>}
<add>
<add>// DaemonLeavesCluster informs the daemon has left the cluster
<add>func (daemon *Daemon) DaemonLeavesCluster() {
<add> // Daemon is in charge of removing the attachable networks with
<add> // connected containers when the node leaves the swarm
<add> daemon.clearAttachableNetworks()
<add> daemon.setClusterProvider(nil)
<add>}
<add>
<add>// setClusterProvider sets a component for querying the current cluster state.
<add>func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
<ide> daemon.clusterProvider = clusterProvider
<ide> daemon.netController.SetClusterProvider(clusterProvider)
<ide> }
<ide><path>daemon/network.go
<ide> func (daemon *Daemon) deleteNetwork(networkID string, dynamic bool) error {
<ide> func (daemon *Daemon) GetNetworks() []libnetwork.Network {
<ide> return daemon.getAllNetworks()
<ide> }
<add>
<add>// clearAttachableNetworks removes the attachable networks
<add>// after disconnecting any connected container
<add>func (daemon *Daemon) clearAttachableNetworks() {
<add> for _, n := range daemon.GetNetworks() {
<add> if !n.Info().Attachable() {
<add> continue
<add> }
<add> for _, ep := range n.Endpoints() {
<add> epInfo := ep.Info()
<add> if epInfo == nil {
<add> continue
<add> }
<add> sb := epInfo.Sandbox()
<add> if sb == nil {
<add> continue
<add> }
<add> containerID := sb.ContainerID()
<add> if err := daemon.DisconnectContainerFromNetwork(containerID, n.ID(), true); err != nil {
<add> logrus.Warnf("Failed to disconnect container %s from swarm network %s on cluster leave: %v",
<add> containerID, n.Name(), err)
<add> }
<add> }
<add> if err := daemon.DeleteManagedNetwork(n.ID()); err != nil {
<add> logrus.Warnf("Failed to remove swarm network %s on cluster leave: %v", n.Name(), err)
<add> }
<add> }
<add>}
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) {
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "true")
<ide> }
<ide>
<add>func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> // Create an attachable swarm network
<add> nwName := "attovl"
<add> out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", nwName)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> // Connect a container to the network
<add> out, err = d.Cmd("run", "-d", "--network", nwName, "--name", "c1", "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> // Leave the swarm
<add> err = d.Leave(true)
<add> c.Assert(err, checker.IsNil)
<add>
<add> // Check the container is disconnected
<add> out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(out), checker.Equals, "<no value>")
<add>
<add> // Check the network is gone
<add> out, err = d.Cmd("network", "ls", "--format", "{{.Name}}")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(out, checker.Not(checker.Contains), nwName)
<add>}
<add>
<ide> func (s *DockerSwarmSuite) TestSwarmRemoveInternalNetwork(c *check.C) {
<ide> d := s.AddDaemon(c, true, true)
<ide> | 5 |
Javascript | Javascript | make message non-enumerable | 22da2f731d90235289a95bffe1ae3750a62a33bc | <ide><path>lib/internal/errors.js
<ide> function exceptionWithHostPort(err, syscall, address, port, additional) {
<ide> }
<ide>
<ide> /**
<del> * @param {number|string} err - A libuv error number or a c-ares error code
<add> * @param {number|string} code - A libuv error number or a c-ares error code
<ide> * @param {string} syscall
<ide> * @param {string} [hostname]
<ide> * @returns {Error}
<ide> */
<del>function dnsException(err, syscall, hostname) {
<del> // eslint-disable-next-line no-restricted-syntax
<del> const ex = new Error();
<add>function dnsException(code, syscall, hostname) {
<add> let message;
<ide> // FIXME(bnoordhuis) Remove this backwards compatibility nonsense and pass
<ide> // the true error to the user. ENOTFOUND is not even a proper POSIX error!
<del> if (err === UV_EAI_MEMORY ||
<del> err === UV_EAI_NODATA ||
<del> err === UV_EAI_NONAME) {
<del> err = 'ENOTFOUND'; // Fabricated error name.
<add> if (code === UV_EAI_MEMORY ||
<add> code === UV_EAI_NODATA ||
<add> code === UV_EAI_NONAME) {
<add> code = 'ENOTFOUND'; // Fabricated error name.
<ide> }
<del> if (typeof err === 'string') { // c-ares error code.
<del> const errHost = hostname ? ` ${hostname}` : '';
<del> ex.message = `${syscall} ${err}${errHost}`;
<del> // TODO(joyeecheung): errno is supposed to be a number, like in uvException
<del> ex.code = ex.errno = err;
<del> ex.syscall = syscall;
<add> if (typeof code === 'string') { // c-ares error code.
<add> message = `${syscall} ${code}${hostname ? ` ${hostname}` : ''}`;
<ide> } else { // libuv error number
<del> const code = lazyInternalUtil().getSystemErrorName(err);
<del> ex.message = `${syscall} ${code}`;
<del> // TODO(joyeecheung): errno is supposed to be err, like in uvException
<del> ex.code = ex.errno = code;
<del> ex.syscall = syscall;
<add> code = lazyInternalUtil().getSystemErrorName(code);
<add> message = `${syscall} ${code}`;
<ide> }
<add> // eslint-disable-next-line no-restricted-syntax
<add> const ex = new Error(message);
<add> // TODO(joyeecheung): errno is supposed to be a number / err, like in
<add> // uvException.
<add> ex.errno = code;
<add> ex.code = code;
<add> ex.syscall = syscall;
<ide> if (hostname) {
<ide> ex.hostname = hostname;
<ide> }
<ide><path>test/common/index.js
<ide> exports.expectsError = function expectsError(fn, settings, exact) {
<ide> fn = undefined;
<ide> }
<ide> function innerFn(error) {
<add> const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
<add> assert.strictEqual(descriptor.enumerable,
<add> false, 'The error message should be non-enumerable');
<ide> if ('type' in settings) {
<ide> const type = settings.type;
<ide> if (type !== Error && !Error.isPrototypeOf(type)) {
<ide><path>test/parallel/test-dns-lookup.js
<ide> dns.lookup('example.com', common.mustCall((error, result, addressType) => {
<ide> assert(error);
<ide> assert.strictEqual(tickValue, 1);
<ide> assert.strictEqual(error.code, 'ENOENT');
<add> const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
<add> assert.strictEqual(descriptor.enumerable,
<add> false, 'The error message should be non-enumerable');
<ide> }));
<ide>
<ide> // Make sure that the error callback is called
<ide><path>test/parallel/test-dns-resolveany-bad-ancount.js
<ide> server.bind(0, common.mustCall(() => {
<ide> assert.strictEqual(err.code, 'EBADRESP');
<ide> assert.strictEqual(err.syscall, 'queryAny');
<ide> assert.strictEqual(err.hostname, 'example.org');
<add> const descriptor = Object.getOwnPropertyDescriptor(err, 'message');
<add> assert.strictEqual(descriptor.enumerable,
<add> false, 'The error message should be non-enumerable');
<ide> server.close();
<ide> }));
<ide> })); | 4 |
Go | Go | add build flag to exec test | ecdbc1a0aff40fa28389d1971528641e2824e5a9 | <ide><path>integration-cli/docker_api_exec_test.go
<add>// +build !test_no_exec
<add>
<ide> package main
<ide>
<ide> import (
<ide><path>integration-cli/docker_cli_exec_test.go
<add>// +build !test_no_exec
<add>
<ide> package main
<ide>
<ide> import ( | 2 |
Java | Java | introduce forwardedheaderfilter for webflux | e70210a1da994ea52e1ade30b052bea9e12e9d1d | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.net.URISyntaxException;
<add>import java.util.LinkedList;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.function.Consumer;
<ide>
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<del>import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<ide>
<ide> /**
<ide> * Package-private default implementation of {@link ServerHttpRequest.Builder}.
<ide> */
<ide> class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder {
<ide>
<del> private final ServerHttpRequest delegate;
<add> private URI uri;
<add>
<add> private HttpHeaders httpHeaders;
<add>
<add> private String httpMethodValue;
<add>
<add> private final MultiValueMap<String, HttpCookie> cookies;
<ide>
<ide> @Nullable
<del> private HttpMethod httpMethod;
<add> private final InetSocketAddress remoteAddress;
<ide>
<ide> @Nullable
<del> private String path;
<add> private String uriPath;
<ide>
<ide> @Nullable
<ide> private String contextPath;
<ide>
<del> @Nullable
<del> private HttpHeaders httpHeaders;
<add> private Flux<DataBuffer> body;
<add>
<add> public DefaultServerHttpRequestBuilder(ServerHttpRequest original) {
<add> Assert.notNull(original, "ServerHttpRequest is required");
<add>
<add> this.uri = original.getURI();
<add> this.httpMethodValue = original.getMethodValue();
<add> this.remoteAddress = original.getRemoteAddress();
<add> this.body = original.getBody();
<ide>
<add> this.httpHeaders = new HttpHeaders();
<add> copyMultiValueMap(original.getHeaders(), this.httpHeaders);
<ide>
<del> public DefaultServerHttpRequestBuilder(ServerHttpRequest delegate) {
<del> Assert.notNull(delegate, "ServerHttpRequest delegate is required");
<del> this.delegate = delegate;
<add> this.cookies = new LinkedMultiValueMap<>(original.getCookies().size());
<add> copyMultiValueMap(original.getCookies(), this.cookies);
<add> }
<add>
<add> private static <K, V> void copyMultiValueMap(MultiValueMap<K,V> source,
<add> MultiValueMap<K,V> destination) {
<add>
<add> for (Map.Entry<K, List<V>> entry : source.entrySet()) {
<add> K key = entry.getKey();
<add> List<V> values = new LinkedList<>(entry.getValue());
<add> destination.put(key, values);
<add> }
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public ServerHttpRequest.Builder method(HttpMethod httpMethod) {
<del> this.httpMethod = httpMethod;
<add> this.httpMethodValue = httpMethod.name();
<add> return this;
<add> }
<add>
<add> @Override
<add> public ServerHttpRequest.Builder uri(URI uri) {
<add> this.uri = uri;
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public ServerHttpRequest.Builder path(String path) {
<del> this.path = path;
<add> this.uriPath = path;
<ide> return this;
<ide> }
<ide>
<ide> public ServerHttpRequest.Builder contextPath(String contextPath) {
<ide>
<ide> @Override
<ide> public ServerHttpRequest.Builder header(String key, String value) {
<del> if (this.httpHeaders == null) {
<del> this.httpHeaders = new HttpHeaders();
<del> }
<ide> this.httpHeaders.add(key, value);
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public ServerHttpRequest.Builder headers(Consumer<HttpHeaders> headersConsumer) {
<add> Assert.notNull(headersConsumer, "'headersConsumer' must not be null");
<add> headersConsumer.accept(this.httpHeaders);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public ServerHttpRequest build() {
<ide> URI uriToUse = getUriToUse();
<del> RequestPath path = getRequestPathToUse(uriToUse);
<del> HttpHeaders headers = getHeadersToUse();
<del> return new MutativeDecorator(this.delegate, this.httpMethod, uriToUse, path, headers);
<add> return new DefaultServerHttpRequest(uriToUse, this.contextPath, this.httpHeaders,
<add> this.httpMethodValue, this.cookies, this.remoteAddress, this.body);
<add>
<ide> }
<ide>
<del> @Nullable
<ide> private URI getUriToUse() {
<del> if (this.path == null) {
<del> return null;
<add> if (this.uriPath == null) {
<add> return this.uri;
<ide> }
<del> URI uri = this.delegate.getURI();
<ide> try {
<del> return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
<del> this.path, uri.getQuery(), uri.getFragment());
<add> return new URI(this.uri.getScheme(), this.uri.getUserInfo(), uri.getHost(), uri.getPort(),
<add> uriPath, uri.getQuery(), uri.getFragment());
<ide> }
<ide> catch (URISyntaxException ex) {
<del> throw new IllegalStateException("Invalid URI path: \"" + this.path + "\"");
<del> }
<del> }
<del>
<del> @Nullable
<del> private RequestPath getRequestPathToUse(@Nullable URI uriToUse) {
<del> if (uriToUse == null && this.contextPath == null) {
<del> return null;
<del> }
<del> else if (uriToUse == null) {
<del> return this.delegate.getPath().modifyContextPath(this.contextPath);
<del> }
<del> else {
<del> return RequestPath.parse(uriToUse, this.contextPath);
<del> }
<del> }
<del>
<del> @Nullable
<del> private HttpHeaders getHeadersToUse() {
<del> if (this.httpHeaders != null) {
<del> HttpHeaders headers = new HttpHeaders();
<del> headers.putAll(this.delegate.getHeaders());
<del> headers.putAll(this.httpHeaders);
<del> return headers;
<del> }
<del> else {
<del> return null;
<add> throw new IllegalStateException("Invalid URI path: \"" + this.uriPath + "\"");
<ide> }
<ide> }
<ide>
<add> private static class DefaultServerHttpRequest extends AbstractServerHttpRequest {
<ide>
<del> /**
<del> * An immutable wrapper of a request returning property overrides -- given
<del> * to the constructor -- or original values otherwise.
<del> */
<del> private static class MutativeDecorator extends ServerHttpRequestDecorator {
<del>
<del> @Nullable
<del> private final HttpMethod httpMethod;
<del>
<del> @Nullable
<del> private final URI uri;
<add> private final String methodValue;
<ide>
<del> @Nullable
<del> private final RequestPath requestPath;
<add> private final MultiValueMap<String, HttpCookie> cookies;
<ide>
<ide> @Nullable
<del> private final HttpHeaders httpHeaders;
<del>
<del>
<del> public MutativeDecorator(ServerHttpRequest delegate, @Nullable HttpMethod method,
<del> @Nullable URI uri, @Nullable RequestPath requestPath, @Nullable HttpHeaders httpHeaders) {
<del>
<del> super(delegate);
<del> this.httpMethod = method;
<del> this.uri = uri;
<del> this.requestPath = requestPath;
<del> this.httpHeaders = httpHeaders;
<add> private final InetSocketAddress remoteAddress;
<add>
<add> private final Flux<DataBuffer> body;
<add>
<add> public DefaultServerHttpRequest(URI uri, @Nullable String contextPath,
<add> HttpHeaders headers, String methodValue,
<add> MultiValueMap<String, HttpCookie> cookies, @Nullable InetSocketAddress remoteAddress,
<add> Flux<DataBuffer> body) {
<add> super(uri, contextPath, headers);
<add> this.methodValue = methodValue;
<add> this.cookies = cookies;
<add> this.remoteAddress = remoteAddress;
<add> this.body = body;
<ide> }
<ide>
<ide> @Override
<del> @Nullable
<del> public HttpMethod getMethod() {
<del> return (this.httpMethod != null ? this.httpMethod : super.getMethod());
<add> public String getMethodValue() {
<add> return this.methodValue;
<ide> }
<ide>
<ide> @Override
<del> public URI getURI() {
<del> return (this.uri != null ? this.uri : super.getURI());
<add> protected MultiValueMap<String, HttpCookie> initCookies() {
<add> return this.cookies;
<ide> }
<ide>
<add> @Nullable
<ide> @Override
<del> public RequestPath getPath() {
<del> return (this.requestPath != null ? this.requestPath : super.getPath());
<add> public InetSocketAddress getRemoteAddress() {
<add> return this.remoteAddress;
<ide> }
<ide>
<ide> @Override
<del> public HttpHeaders getHeaders() {
<del> return (this.httpHeaders != null ? this.httpHeaders : super.getHeaders());
<add> public Flux<DataBuffer> getBody() {
<add> return this.body;
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java
<ide> package org.springframework.http.server.reactive;
<ide>
<ide> import java.net.InetSocketAddress;
<add>import java.net.URI;
<add>import java.util.function.Consumer;
<ide>
<ide> import org.springframework.http.HttpCookie;
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.ReactiveHttpInputMessage;
<ide> interface Builder {
<ide> */
<ide> Builder method(HttpMethod httpMethod);
<ide>
<add> /**
<add> * Set the URI to return.
<add> */
<add> Builder uri(URI uri);
<add>
<ide> /**
<ide> * Set the path to use instead of the {@code "rawPath"} of
<ide> * {@link ServerHttpRequest#getURI()}.
<ide> interface Builder {
<ide> */
<ide> Builder header(String key, String value);
<ide>
<add> /**
<add> * Manipulate this request's headers with the given consumer. The
<add> * headers provided to the consumer are "live", so that the consumer can be used to
<add> * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values,
<add> * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other
<add> * {@link HttpHeaders} methods.
<add> * @param headersConsumer a function that consumes the {@code HttpHeaders}
<add> * @return this builder
<add> */
<add> Builder headers(Consumer<HttpHeaders> headersConsumer);
<add>
<ide> /**
<ide> * Build a {@link ServerHttpRequest} decorator with the mutated properties.
<ide> */
<ide><path>spring-web/src/main/java/org/springframework/web/filter/reactive/ForwardedHeaderFilter.java
<add>/*
<add> * Copyright 2002-2017 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.filter.reactive;
<add>
<add>import java.net.URI;
<add>import java.util.Collections;
<add>import java.util.Locale;
<add>import java.util.Set;
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.LinkedCaseInsensitiveMap;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.WebFilter;
<add>import org.springframework.web.server.WebFilterChain;
<add>import org.springframework.web.util.UriComponentsBuilder;
<add>
<add>/**
<add> * Extract values from "Forwarded" and "X-Forwarded-*" headers in order to wrap
<add> * and override the following from the request and response:
<add> * {@link HttpServletRequest#getServerName() getServerName()},
<add> * {@link HttpServletRequest#getServerPort() getServerPort()},
<add> * {@link HttpServletRequest#getScheme() getScheme()},
<add> * {@link HttpServletRequest#isSecure() isSecure()}, and
<add> * {@link HttpServletResponse#sendRedirect(String) sendRedirect(String)}.
<add> * In effect the wrapped request and response reflect the client-originated
<add> * protocol and address.
<add> *
<add> * <p><strong>Note:</strong> This filter can also be used in a
<add> * {@link #setRemoveOnly removeOnly} mode where "Forwarded" and "X-Forwarded-*"
<add> * headers are only eliminated without being used.
<add> * @author Arjen Poutsma
<add> * @see <a href="https://tools.ietf.org/html/rfc7239">https://tools.ietf.org/html/rfc7239</a>
<add> * @since 5.0
<add> */
<add>public class ForwardedHeaderFilter implements WebFilter {
<add>
<add> private static final Set<String> FORWARDED_HEADER_NAMES =
<add> Collections.newSetFromMap(new LinkedCaseInsensitiveMap<>(5, Locale.ENGLISH));
<add>
<add> static {
<add> FORWARDED_HEADER_NAMES.add("Forwarded");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-Host");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-Port");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-Proto");
<add> FORWARDED_HEADER_NAMES.add("X-Forwarded-Prefix");
<add> }
<add>
<add> private boolean removeOnly;
<add>
<add> /**
<add> * Enables mode in which any "Forwarded" or "X-Forwarded-*" headers are
<add> * removed only and the information in them ignored.
<add> * @param removeOnly whether to discard and ignore forwarded headers
<add> */
<add> public void setRemoveOnly(boolean removeOnly) {
<add> this.removeOnly = removeOnly;
<add> }
<add>
<add> @Override
<add> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<add>
<add> if (shouldNotFilter(exchange.getRequest())) {
<add> return chain.filter(exchange);
<add> }
<add>
<add> if (this.removeOnly) {
<add> ServerWebExchange withoutForwardHeaders = exchange.mutate()
<add> .request(builder -> builder.headers(
<add> headers -> {
<add> for (String headerName : FORWARDED_HEADER_NAMES) {
<add> headers.remove(headerName);
<add> }
<add> })).build();
<add> return chain.filter(withoutForwardHeaders);
<add> }
<add> else {
<add> URI uri = UriComponentsBuilder.fromHttpRequest(exchange.getRequest()).build().toUri();
<add> String prefix = getForwardedPrefix(exchange.getRequest().getHeaders());
<add>
<add> ServerWebExchange withChangedUri = exchange.mutate()
<add> .request(builder -> {
<add> builder.uri(uri);
<add> if (prefix != null) {
<add> builder.path(prefix + uri.getPath());
<add> builder.contextPath(prefix);
<add> }
<add> }).build();
<add> return chain.filter(withChangedUri);
<add> }
<add>
<add> }
<add>
<add> private boolean shouldNotFilter(ServerHttpRequest request) {
<add> return request.getHeaders().keySet().stream()
<add> .noneMatch(FORWARDED_HEADER_NAMES::contains);
<add> }
<add>
<add> @Nullable
<add> private static String getForwardedPrefix(HttpHeaders headers) {
<add> String prefix = headers.getFirst("X-Forwarded-Prefix");
<add> if (prefix != null) {
<add> while (prefix.endsWith("/")) {
<add> prefix = prefix.substring(0, prefix.length() - 1);
<add> }
<add> }
<add> return prefix;
<add> }
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.java
<ide> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> String method = formData.getFirst(this.methodParamName);
<ide> return StringUtils.hasLength(method) ? mapExchange(exchange, method) : exchange;
<ide> })
<del> .flatMap((exchange1) -> chain.filter(exchange1));
<add> .flatMap(chain::filter);
<ide> }
<ide>
<ide> private ServerWebExchange mapExchange(ServerWebExchange exchange, String methodParamValue) {
<ide><path>spring-web/src/test/java/org/springframework/web/filter/reactive/ForwardedHeaderFilterTests.java
<add>/*
<add> * Copyright 2002-2017 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.filter.reactive;
<add>
<add>import java.net.URI;
<add>import java.time.Duration;
<add>
<add>import org.junit.Test;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<add>import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.WebFilterChain;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * @author Arjen Poutsma
<add> */
<add>public class ForwardedHeaderFilterTests {
<add>
<add> private final ForwardedHeaderFilter filter = new ForwardedHeaderFilter();
<add>
<add> private final TestWebFilterChain filterChain = new TestWebFilterChain();
<add>
<add>
<add> @Test
<add> public void removeOnly() {
<add> MockServerWebExchange exchange = MockServerHttpRequest.get("/")
<add> .header("Forwarded", "for=192.0.2.60;proto=http;by=203.0.113.43")
<add> .header("X-Forwarded-Host", "example.com")
<add> .header("X-Forwarded-Port", "8080")
<add> .header("X-Forwarded-Proto", "http")
<add> .header("X-Forwarded-Prefix", "prefix")
<add> .toExchange();
<add>
<add> this.filter.setRemoveOnly(true);
<add> this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
<add>
<add> HttpHeaders result = this.filterChain.getHeaders();
<add> assertNotNull(result);
<add> assertFalse(result.containsKey("Forwarded"));
<add> assertFalse(result.containsKey("X-Forwarded-Host"));
<add> assertFalse(result.containsKey("X-Forwarded-Port"));
<add> assertFalse(result.containsKey("X-Forwarded-Proto"));
<add> assertFalse(result.containsKey("X-Forwarded-Prefix"));
<add> }
<add>
<add> @Test
<add> public void xForwardedRequest() throws Exception {
<add> MockServerWebExchange exchange = MockServerHttpRequest.get("http://example.com/path")
<add> .header("X-Forwarded-Host", "84.198.58.199")
<add> .header("X-Forwarded-Port", "443")
<add> .header("X-Forwarded-Proto", "https")
<add> .toExchange();
<add>
<add> this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
<add>
<add> URI uri = this.filterChain.uri;
<add> assertEquals(new URI("https://84.198.58.199/path"), uri);
<add> }
<add>
<add> @Test
<add> public void forwardedRequest() throws Exception {
<add> MockServerWebExchange exchange = MockServerHttpRequest.get("http://example.com/path")
<add> .header("Forwarded", "host=84.198.58.199;proto=https")
<add>
<add> .toExchange();
<add>
<add> this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
<add>
<add> URI uri = this.filterChain.uri;
<add> assertEquals(new URI("https://84.198.58.199/path"), uri);
<add> }
<add>
<add> @Test
<add> public void requestUriWithForwardedPrefix() throws Exception {
<add> MockServerWebExchange exchange = MockServerHttpRequest.get("http://example.com/path")
<add> .header("X-Forwarded-Prefix", "/prefix")
<add> .toExchange();
<add>
<add> this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
<add>
<add> URI uri = this.filterChain.uri;
<add> assertEquals(new URI("http://example.com/prefix/path"), uri);
<add> }
<add>
<add> @Test
<add> public void requestUriWithForwardedPrefixTrailingSlash() throws Exception {
<add> MockServerWebExchange exchange = MockServerHttpRequest.get("http://example.com/path")
<add> .header("X-Forwarded-Prefix", "/prefix/")
<add> .toExchange();
<add>
<add> this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
<add>
<add> URI uri = this.filterChain.uri;
<add> assertEquals(new URI("http://example.com/prefix/path"), uri);
<add> }
<add>
<add>
<add> private static class TestWebFilterChain implements WebFilterChain {
<add>
<add> @Nullable
<add> private HttpHeaders httpHeaders;
<add>
<add> @Nullable
<add> private URI uri;
<add>
<add> @Nullable
<add> public HttpHeaders getHeaders() {
<add> return this.httpHeaders;
<add> }
<add>
<add> @Nullable
<add> public URI getUri() {
<add> return this.uri;
<add> }
<add>
<add> @Override
<add> public Mono<Void> filter(ServerWebExchange exchange) {
<add> this.httpHeaders = exchange.getRequest().getHeaders();
<add> this.uri = exchange.getRequest().getURI();
<add> return Mono.empty();
<add> }
<add> }
<add>
<add>
<add>
<add>}
<ide>\ No newline at end of file | 5 |
PHP | PHP | fix selected values in some cases | 6d8062dd9c3bb40d0feb030c9b5fa7d923c4ae58 | <ide><path>src/View/Widget/DateTime.php
<ide> protected function _deconstructDate($value, $options) {
<ide> if (isset($value['year'], $value['month'], $value['day'])) {
<ide> $date->setDate($value['year'], $value['month'], $value['day']);
<ide> }
<add> if (!isset($value['second'])) {
<add> $value['second'] = 0;
<add> }
<add> if (isset($value['meridian'])) {
<add> $isAm = strtolower($value['meridian']) === 'am';
<add> $value['hour'] = $isAm ? $value['hour'] : $value['hour'] + 12;
<add> }
<ide> if (isset($value['hour'], $value['minute'], $value['second'])) {
<ide> $date->setTime($value['hour'], $value['minute'], $value['second']);
<ide> }
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testDatetimeMinuteInterval() {
<ide> extract($this->dateRegex);
<ide> $now = strtotime('now');
<ide>
<del> $result = $this->Form->dateTime('Contact.date', 'DMY', '12', array('interval' => 5, 'value' => ''));
<add> $result = $this->Form->dateTime('Contact.date', 'DMY', '12', array(
<add> 'interval' => 5,
<add> 'value' => ''
<add> ));
<ide> $expected = array(
<del> array('select' => array('name' => 'Contact[date][day]')),
<del> $daysRegex,
<del> array('option' => array('value' => '')),
<add> array('select' => array('name' => 'Contact[date][month]')),
<add> $monthsRegex,
<add> array('option' => array('selected' => 'selected', 'value' => '')),
<ide> '/option',
<ide> '*/select',
<ide>
<del> array('select' => array('name' => 'Contact[date][month]')),
<del> $monthsRegex,
<del> array('option' => array('value' => '')),
<add> array('select' => array('name' => 'Contact[date][day]')),
<add> $daysRegex,
<add> array('option' => array('selected' => 'selected', 'value' => '')),
<ide> '/option',
<ide> '*/select',
<ide>
<ide> array('select' => array('name' => 'Contact[date][year]')),
<ide> $yearsRegex,
<del> array('option' => array('value' => '')),
<add> array('option' => array('selected' => 'selected', 'value' => '')),
<ide> '/option',
<ide> '*/select',
<ide>
<ide> array('select' => array('name' => 'Contact[date][hour]')),
<ide> $hoursRegex,
<del> array('option' => array('value' => '')),
<add> array('option' => array('selected' => 'selected', 'value' => '')),
<ide> '/option',
<ide> '*/select',
<ide>
<ide> array('select' => array('name' => 'Contact[date][minute]')),
<ide> $minutesRegex,
<del> array('option' => array('value' => '')),
<add> array('option' => array('selected' => 'selected', 'value' => '')),
<ide> '/option',
<ide> array('option' => array('value' => '00')),
<ide> '00',
<ide> public function testDatetimeMinuteInterval() {
<ide> '10',
<ide> '/option',
<ide> '*/select',
<del>
<del> array('select' => array('name' => 'Contact[date][meridian]')),
<del> $meridianRegex,
<del> array('option' => array('value' => '')),
<del> '/option',
<del> '*/select'
<ide> );
<ide> $this->assertTags($result, $expected);
<del> $this->assertNotRegExp('/<option[^<>]+value=""[^<>]+selected="selected"[^>]*>/', $result);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Widget/DateTimeTest.php
<ide> public function testRenderSelected($selected) {
<ide> $this->assertContains('<option value="45" selected="selected">45</option>', $result);
<ide> }
<ide>
<add>/**
<add> * Test that render() works with an array for val that is missing seconds.
<add> *
<add> * @return void
<add> */
<add> public function testRenderSelectedNoSeconds() {
<add> $selected = [
<add> 'year' => '2014', 'month' => '01', 'day' => '20',
<add> 'hour' => '12', 'minute' => '30'
<add> ];
<add> $result = $this->DateTime->render(['val' => $selected]);
<add> $this->assertContains('<option value="2014" selected="selected">2014</option>', $result);
<add> $this->assertContains('<option value="01" selected="selected">1</option>', $result);
<add> $this->assertContains('<option value="20" selected="selected">20</option>', $result);
<add> $this->assertContains('<option value="12" selected="selected">12</option>', $result);
<add> $this->assertContains('<option value="30" selected="selected">30</option>', $result);
<add> }
<add>
<add>/**
<add> * Test that render() adjusts hours based on meridian
<add> *
<add> * @return void
<add> */
<add> public function testRenderSelectedMeridian() {
<add> $selected = [
<add> 'year' => '2014', 'month' => '01', 'day' => '20',
<add> 'hour' => '7', 'minute' => '30', 'meridian' => 'pm'
<add> ];
<add> $result = $this->DateTime->render(['val' => $selected]);
<add> $this->assertContains('<option value="2014" selected="selected">2014</option>', $result);
<add> $this->assertContains('<option value="01" selected="selected">1</option>', $result);
<add> $this->assertContains('<option value="20" selected="selected">20</option>', $result);
<add> $this->assertContains('<option value="19" selected="selected">19</option>', $result);
<add> }
<add>
<ide> /**
<ide> * Test rendering widgets with empty values.
<ide> * | 3 |
PHP | PHP | modify option to fullbase for consistency | b96873088bc0282aa03b72b4bb630e8d737090d8 | <ide><path>src/View/Helper/UrlHelper.php
<ide> class UrlHelper extends Helper
<ide> *
<ide> * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
<ide> * escaped afterwards before being displayed.
<del> * - `full`: If true, the full base URL will be prepended to the result
<add> * - `fullBase`: If true, the full base URL will be prepended to the result
<ide> *
<ide> * @param string|array|null $url Either a relative string url like `/products/view/23` or
<ide> * an array of URL parameters. Using an array for URLs will allow you to leverage
<ide> class UrlHelper extends Helper
<ide> public function build($url = null, $options = false)
<ide> {
<ide> $defaults = [
<del> 'full' => false,
<add> 'fullBase' => false,
<ide> 'escape' => true,
<ide> ];
<ide> if (!is_array($options)) {
<del> $options = ['full' => $options];
<add> $options = ['fullBase' => $options];
<ide> }
<ide> $options += $defaults;
<ide>
<del> $url = Router::url($url, $options['full']);
<add> $url = Router::url($url, $options['fullBase']);
<ide> if ($options['escape']) {
<ide> $url = h($url);
<ide> } | 1 |
Ruby | Ruby | add test cases for hash#asset_valid_keys | fedb16ae12e60de95e4b1177a131e896da3a8012 | <ide><path>activesupport/test/core_ext/hash_ext_test.rb
<ide> def test_assert_valid_keys
<ide> { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
<ide> { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
<ide> end
<add> # not all valid keys are required to be present
<add> assert_nothing_raised do
<add> { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny, :sunny ])
<add> { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny, :sunny)
<add> end
<ide>
<ide> exception = assert_raise ArgumentError do
<ide> { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
<ide> def test_assert_valid_keys
<ide> { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
<ide> end
<ide> assert_equal "Unknown key: :failore. Valid keys are: :failure, :funny", exception.message
<add>
<add> exception = assert_raise ArgumentError do
<add> { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure ])
<add> end
<add> assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
<add>
<add> exception = assert_raise ArgumentError do
<add> { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure)
<add> end
<add> assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
<ide> end
<ide>
<ide> def test_assorted_keys_not_stringified | 1 |
Javascript | Javascript | remove log in webxrmanager | 7dd52e4a5a3fc3aa68c3d69078e780c9b792d881 | <ide><path>src/renderers/webxr/WebXRManager.js
<ide> function WebXRManager( renderer, gl ) {
<ide> //
<ide>
<ide> const inputSources = session.inputSources;
<del> //console.log(inputSources);
<ide>
<ide> for ( let i = 0; i < controllers.length; i ++ ) {
<ide> | 1 |
Python | Python | add a -1 option to run glances in per cpu mode | 70db4139f7c13ff89d670d33755b2fcd84626380 | <ide><path>glances/glances.py
<ide> def __init__(self, refresh_time=1, use_bold=1):
<ide> self.fs_tag = fs_tag
<ide> self.log_tag = True
<ide> self.help_tag = False
<del> self.percpu_tag = False
<add> self.percpu_tag = percpu_tag
<ide> self.process_tag = process_tag
<ide> self.net_byteps_tag = network_bytepersec_tag
<ide> self.network_stats_combined = False
<ide> def printSyntax():
<ide> print(_("\t-v\t\tDisplay the version and exit"))
<ide> print(_("\t-y\t\tEnable the hddtemp module (needs running hddtemp daemon)"))
<ide> print(_("\t-z\t\tDo not use the bold color attribute"))
<add> print(_("\t-1\t\tStart Glances in per CPU mode"))
<ide>
<ide>
<ide> def end():
<ide> def main():
<ide> global htmloutput, csvoutput
<ide> global html_tag, csv_tag, server_tag, client_tag
<ide> global psutil_get_io_counter_tag, psutil_mem_vm
<del> global fs_tag, diskio_tag, network_tag, network_bytepersec_tag, sensors_tag
<del> global hddtemp_tag, process_tag
<add> global percpu_tag, fs_tag, diskio_tag, network_tag, network_bytepersec_tag
<add> global sensors_tag, hddtemp_tag, process_tag
<ide> global refresh_time, client, server, server_port, server_ip
<ide> global last_update_times
<ide>
<ide> # create update times dict
<ide> last_update_times = {}
<ide>
<ide> # Set default tags
<add> percpu_tag = False
<ide> fs_tag = True
<ide> diskio_tag = True
<ide> network_tag = True
<ide> def main():
<ide>
<ide> # Manage args
<ide> try:
<del> opts, args = getopt.getopt(sys.argv[1:], "B:bdeymnho:f:t:vsc:p:C:P:z:r",
<add> opts, args = getopt.getopt(sys.argv[1:], "B:bdeymnho:f:t:vsc:p:C:P:z:r1",
<ide> ["bind", "bytepersec", "diskio", "mount",
<ide> "sensors", "hddtemp", "netrate", "help", "output",
<ide> "file", "time", "version", "server",
<ide> "client", "port", "config", "password",
<del> "nobold", "noproc"])
<add> "nobold", "noproc", "percpu"])
<ide> except getopt.GetoptError as err:
<ide> # Print help information and exit:
<ide> print(str(err))
<ide> def main():
<ide> use_bold = False
<ide> elif opt in ("-r", "--noproc"):
<ide> process_tag = False
<add> elif opt in ("-1", "--percpu"):
<add> percpu_tag = True
<ide> else:
<ide> printSyntax()
<ide> sys.exit(0) | 1 |
PHP | PHP | import closure at the top | 5d26f491b27accedb44e2c444820c18d8771a49e | <ide><path>src/Illuminate/Database/Eloquent/FactoryBuilder.php
<ide>
<ide> namespace Illuminate\Database\Eloquent;
<ide>
<add>use Closure;
<ide> use Faker\Generator as Faker;
<ide> use InvalidArgumentException;
<ide>
<ide> protected function makeInstance(array $attributes = [])
<ide> protected function evaluateClosures(array $attributes)
<ide> {
<ide> return array_map(function ($attribute) use ($attributes) {
<del> return $attribute instanceof \Closure ? $attribute($attributes) : $attribute;
<add> return $attribute instanceof Closure ? $attribute($attributes) : $attribute;
<ide> }, $attributes);
<ide> }
<ide> } | 1 |
Text | Text | improve pr template with details from contributing | 670d8f1dbef0ee56d5dc5ca2c2eac1490fb9685c | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> ## FreeCodeCamp Pull Request template
<del>Please, go through steps before you submit a PR.
<add>Please, go through these steps before you submit a PR.
<ide>
<ide> 1. Make sure that your PR is not a duplicate.
<del>2. If not then:
<add>2. If not, then make sure that:
<ide>
<del> 2.1. Make sure you've done your changes in a separate branch, like `fix/signin-issue` or `feature/issue-templates`.
<add> 2.1. You have done your changes in a separate branch. Branches MUST have descriptive names that start with either the `fix/` or `feature/` prefixes. Good examples are: `fix/signin-issue` or `feature/issue-templates`.
<ide>
<del> 2.2. You have a descriptive commit message.
<add> 2.2. You have a descriptive commit message with a short title (first line).
<ide>
<ide> 2.3. You have only one commit (if not, [squash](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/git-rebase#squashing-multiple-commits-into-one) them into one commit).
<ide>
<del> 2.4. Make sure `npm test` doesn't throw any error. If it does, fix them first and amend your commit.
<add> 2.4. `npm test` doesn't throw any error. If it does, fix them first and amend your commit (`git commit --amend`).
<ide>
<del>3. **After** these steps you're ready to open a pull request. ***Don't*** forget to remove this template first.
<add>3. **After** these steps, you're ready to open a pull request.
<ide>
<del> 3.1. Give a descriptive title to your PR.
<add> 3.1. Your pull request MUST NOT target the `master` branch on FreeCodeCamp's repository. You probably want to target `staging` instead.
<ide>
<del> 3.2. Provide a description of your changes.
<add> 3.2. Give a descriptive title to your PR.
<ide>
<del> 3.3. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such).
<add> 3.3. Provide a description of your changes.
<add>
<add> 3.4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such).
<add>
<add>IMPORTANT: Please review the [CONTRIBUTING.md](../CONTRIBUTING.md) file for detailed contributing guidelines.
<add>
<add>**PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING** | 1 |
Ruby | Ruby | allow ruby 2.6.10 on < ventura | 476b5e74246b72c50fc02d7c0b9b6b8ae1291e18 | <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb
<ide> def check_if_xcode_needs_clt_installed
<ide> end
<ide>
<ide> def check_ruby_version
<del> # TODO: update portable-ruby to 2.6.10 when Ventura reaches RC
<del> required_version = if MacOS.version >= :ventura &&
<del> ENV["HOMEBREW_RUBY_PATH"].to_s.exclude?("/vendor/portable-ruby/")
<del> "2.6.10"
<del> else
<del> HOMEBREW_REQUIRED_RUBY_VERSION
<del> end
<del> return if RUBY_VERSION == required_version
<add> return if RUBY_VERSION == HOMEBREW_REQUIRED_RUBY_VERSION
<add> return if RUBY_VERSION == "2.6.10" # TODO: require 2.6.10
<ide> return if Homebrew::EnvConfig.developer? && OS::Mac.version.prerelease?
<ide>
<ide> <<~EOS
<ide> Ruby version #{RUBY_VERSION} is unsupported on macOS #{MacOS.version}. Homebrew
<del> is developed and tested on Ruby #{required_version}, and may not work correctly
<add> is developed and tested on Ruby #{HOMEBREW_REQUIRED_RUBY_VERSION}, and may not work correctly
<ide> on other Rubies. Patches are accepted as long as they don't cause breakage
<ide> on supported Rubies.
<ide> EOS | 1 |
Ruby | Ruby | add tests for aliased types | f60190873828622d9abb36ba924334f2ef776742 | <ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def test_schema_dump_does_not_include_limit_for_float_field
<ide> assert_match %r{t\.float\s+"temperature"$}, output
<ide> end
<ide>
<add> def test_schema_dump_aliased_types
<add> output = standard_dump
<add> assert_match %r{t\.binary\s+"blob_data"$}, output
<add> assert_match %r{t\.decimal\s+"numeric_number"}, output
<add> end
<add>
<ide> if ActiveRecord::Base.connection.supports_expression_index?
<ide> def test_schema_dump_expression_indices
<ide> index_definition = dump_table_schema("companies").split(/\n/).grep(/t\.index.*company_expression_index/).first.strip
<ide><path>activerecord/test/schema/schema.rb
<ide> t.string :name
<ide> t.binary :data
<ide> t.binary :short_data, limit: 2048
<add> t.blob :blob_data
<ide> end
<ide>
<ide> create_table :birds, force: true do |t|
<ide> t.decimal :my_house_population, precision: 2, scale: 0
<ide> t.decimal :decimal_number
<ide> t.decimal :decimal_number_with_default, precision: 3, scale: 2, default: 2.78
<add> t.numeric :numeric_number
<ide> t.float :temperature
<ide> t.decimal :decimal_number_big_precision, precision: 20
<ide> # Oracle/SQLServer supports precision up to 38 | 2 |
Mixed | Ruby | make possibile to get different message verifiers | 2be4916e8ee6f36b090df91d28d0c484983dcb5a | <ide><path>railties/CHANGELOG.md
<del>* Add `Application#message_verifier` method to return a application's message verifier.
<add>* Add `Application#message_verifier` method to return a message verifier.
<ide>
<ide> This verifier can be used to generate and verify signed messages in the application.
<ide>
<ide> message = Rails.application.message_verifier.generate('my sensible data')
<ide> Rails.application.message_verifier.verify(message)
<ide> # => 'my sensible data'
<ide>
<add> It is recommended to not use the same verifier to different things, so you can get different
<add> verifiers passing the name argument.
<add>
<add> message = Rails.application.message_verifier('cookies').generate('my sensible cookie data')
<add>
<add> By default all the verifiers will share the same salt, so messages generates by one can be
<add> verifier by another one.
<add>
<ide> See the `ActiveSupport::MessageVerifier` documentation to more information.
<ide>
<ide> *Rafael Mendonça França*
<ide><path>railties/lib/rails/application.rb
<ide> def inherited(base)
<ide>
<ide> def initialize(initial_variable_values = {}, &block)
<ide> super()
<del> @initialized = false
<del> @reloaders = []
<del> @routes_reloader = nil
<del> @app_env_config = nil
<del> @ordered_railties = nil
<del> @railties = nil
<add> @initialized = false
<add> @reloaders = []
<add> @routes_reloader = nil
<add> @app_env_config = nil
<add> @ordered_railties = nil
<add> @railties = nil
<add> @message_verifiers = {}
<ide>
<ide> add_lib_to_load_path!
<ide> ActiveSupport.run_load_hooks(:before_configuration, self)
<ide> def key_generator
<ide> end
<ide> end
<ide>
<del> # Return the application's message verifier.
<add> # Return a message verifier object.
<ide> #
<ide> # This verify can be used to generate and verify signed messages in the application.
<ide> #
<add> # By default all the verifiers will share the same salt.
<add> #
<add> # ==== Parameters
<add> #
<add> # * +verifier_name+ - the name of verifier you want to get.
<add> #
<add> # ==== Examples
<add> #
<ide> # message = Rails.application.message_verifier.generate('my sensible data')
<ide> # Rails.application.message_verifier.verify(message)
<ide> # # => 'my sensible data'
<ide> #
<ide> # See the +ActiveSupport::MessageVerifier+ documentation to more information.
<del> def message_verifier
<del> @message_verifier ||= begin
<add> def message_verifier(verifier_name = 'default')
<add> @message_verifiers[verifier_name] ||= begin
<ide> if config.respond_to?(:message_verifier_salt)
<ide> salt = config.message_verifier_salt
<ide> end
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> assert_equal 'some_value', verifier.verify(last_response.body)
<ide> end
<ide>
<add> test "application verifier can build different verifiers" do
<add> make_basic_app do |app|
<add> app.config.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
<add> app.config.session_store :disabled
<add> end
<add>
<add> assert_equal Rails.application.message_verifier.object_id, Rails.application.message_verifier.object_id
<add> assert_not_equal Rails.application.message_verifier.object_id, Rails.application.message_verifier('text').object_id
<add> end
<add>
<ide> test "protect from forgery is the default in a new app" do
<ide> make_basic_app
<ide> | 3 |
PHP | PHP | fix broken shortcut | 74cd4cd1f4458fcc1c6ad1f526025c2a5aab018b | <ide><path>src/Illuminate/Foundation/Console/ListenerMakeCommand.php
<ide> protected function getOptions()
<ide> return [
<ide> ['event', 'e', InputOption::VALUE_REQUIRED, 'The event class being listened for.'],
<ide>
<del> ['queued', 'q', InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'],
<add> ['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'],
<ide> ];
<ide> }
<ide> } | 1 |
Javascript | Javascript | move require.onerror default to jsonp template | af2a362ba14aac95a5c0cf8aa8d1ed6860c04e21 | <ide><path>lib/JsonpMainTemplatePlugin.js
<ide> JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) {
<ide> "return installedChunks[chunkId][2] = promise;"
<ide> ]);
<ide> });
<add> this.plugin("require-extensions", function(source, chunk) {
<add> if(chunk.chunks.length === 0) return source;
<add> return this.asString([
<add> source,
<add> "",
<add> "// on error function for async loading",
<add> this.requireFn + ".oe = function(err) { console.error(err); throw err; };"
<add> ]);
<add> });
<ide> mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
<ide> if(chunk.chunks.length > 0) {
<ide> var jsonpFunction = this.outputOptions.jsonpFunction;
<ide><path>lib/MainTemplate.js
<ide> function MainTemplate(outputOptions) {
<ide> buf.push(this.requireFn + ".p = " + JSON.stringify(publicPath) + ";");
<ide> return this.asString(buf);
<ide> });
<del> this.plugin("require-extensions", function(source, chunk) {
<del> if(chunk.chunks.length === 0) return source;
<del> return this.asString([
<del> source,
<del> "",
<del> "// on error function for async loading",
<del> this.requireFn + ".oe = function(err) { console.error(err); throw err; };"
<del> ]);
<del> });
<ide> }
<ide> module.exports = MainTemplate;
<ide> | 2 |
Java | Java | clarify resolvabletype.resolve() java doc | ee8f1aa61a4c9aad2ea09ce24aa4f247b3c17dfc | <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> public Class<?> resolveGeneric(int... indexes) {
<ide> /**
<ide> * Resolve this type to a {@link java.lang.Class}, returning {@code null} if the type
<ide> * cannot be resolved. This method will consider bounds of {@link TypeVariable}s and
<del> * {@link WildcardType}s if direct resolution fails.
<add> * {@link WildcardType}s if direct resolution fails, however, bounds of Object.class
<add> * will be ignored.
<ide> * @return the resolved {@link Class} or {@code null}
<ide> * @see #resolve(Class)
<ide> * @see #resolveGeneric(int...)
<ide> public Class<?> resolve() {
<ide> /**
<ide> * Resolve this type to a {@link java.lang.Class}, returning the specified
<ide> * {@code fallback} if the type cannot be resolved. This method will consider bounds
<del> * of {@link TypeVariable}s and {@link WildcardType}s if direct resolution fails.
<add> * of {@link TypeVariable}s and {@link WildcardType}s if direct resolution fails,
<add> * however, bounds of Object.class will be ignored.
<ide> * @param fallback the fallback class to use if resolution fails (may be {@code null})
<ide> * @return the resolved {@link Class} or the {@code fallback}
<ide> * @see #resolve() | 1 |
Text | Text | fix slight grammatical error | 571aabfdd35f6379b885722ece8e121388ffd932 | <ide><path>threejs/lessons/threejs-primitives.md
<ide> primitives.
<ide> Here we are extruding a heart shape. Note this is the basis
<ide> for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.</div>
<ide> <div data-primitive="IcosahedronBufferGeometry">An icosahedron (20 sides)</div>
<del><div data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<add><div data-primitive="LatheBufferGeometry">A shape generated by spinning a line. Examples would be: lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<ide> <div data-primitive="OctahedronBufferGeometry">An Octahedron (8 sides)</div>
<ide> <div data-primitive="ParametricBufferGeometry">A surface generated by providing a function that takes a 2D point from a grid and returns the corresponding 3d point.</div>
<ide> <div data-primitive="PlaneBufferGeometry">A 2D plane</div> | 1 |
Go | Go | add a test using the flags | 6228761f67bb5f2af6c3105de556fa3fedb12069 | <ide><path>integration-cli/docker_cli_save_load_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<del>// save a repo and try to load it
<del>func TestSaveAndLoadRepo(t *testing.T) {
<add>// save a repo and try to load it using stdout
<add>func TestSaveAndLoadRepoStdout(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to create a container: %v %v", out, err))
<ide> func TestSaveAndLoadRepo(t *testing.T) {
<ide>
<ide> os.Remove("/tmp/foobar-save-load-test.tar")
<ide>
<del> logDone("save - save a repo")
<del> logDone("load - load a repo")
<add> logDone("save - save a repo using stdout")
<add> logDone("load - load a repo using stdout")
<add>}
<add>
<add>// save a repo and try to load it using flags
<add>func TestSaveAndLoadRepoFlags(t *testing.T) {
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to create a container: %v %v", out, err))
<add>
<add> cleanedContainerID := stripTrailingCharacters(out)
<add>
<add> repoName := "foobar-save-load-test"
<add>
<add> inspectCmd := exec.Command(dockerBinary, "inspect", cleanedContainerID)
<add> out, _, err = runCommandWithOutput(inspectCmd)
<add> errorOut(err, t, fmt.Sprintf("output should've been a container id: %v %v", cleanedContainerID, err))
<add>
<add> commitCmd := exec.Command(dockerBinary, "commit", cleanedContainerID, repoName)
<add> out, _, err = runCommandWithOutput(commitCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to commit container: %v %v", out, err))
<add>
<add> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<add> before, _, err := runCommandWithOutput(inspectCmd)
<add> errorOut(err, t, fmt.Sprintf("the repo should exist before saving it: %v %v", before, err))
<add>
<add> saveCmdTemplate := `%v save -o /tmp/foobar-save-load-test.tar %v`
<add> saveCmdFinal := fmt.Sprintf(saveCmdTemplate, dockerBinary, repoName)
<add> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<add> out, _, err = runCommandWithOutput(saveCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to save repo: %v %v", out, err))
<add>
<add> deleteImages(repoName)
<add>
<add> loadCmdFinal := `docker load -i /tmp/foobar-save-load-test.tar`
<add> loadCmd := exec.Command("bash", "-c", loadCmdFinal)
<add> out, _, err = runCommandWithOutput(loadCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to load repo: %v %v", out, err))
<add>
<add> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<add> after, _, err := runCommandWithOutput(inspectCmd)
<add> errorOut(err, t, fmt.Sprintf("the repo should exist after loading it: %v %v", after, err))
<add>
<add> if before != after {
<add> t.Fatalf("inspect is not the same after a save / load")
<add> }
<add>
<add> deleteContainer(cleanedContainerID)
<add> deleteImages(repoName)
<add>
<add> os.Remove("/tmp/foobar-save-load-test.tar")
<add>
<add> logDone("save - save a repo using -o")
<add> logDone("load - load a repo using -i")
<ide> } | 1 |
Text | Text | add changes for 1.6.8 | 22450e5b7c8486a721db74be32333007273ba584 | <ide><path>CHANGELOG.md
<add><a name="1.6.8"></a>
<add># 1.6.8 beneficial-tincture (2017-12-18)
<add>
<add>
<add>## Bug Fixes
<add>- **$location:**
<add> - always decode special chars in `$location.url(value)`
<add> ([2bdf71](https://github.com/angular/angular.js/commit/2bdf7126878c87474bb7588ce093d0a3c57b0026))
<add> - decode non-component special chars in Hashbang URLS
<add> ([57b626](https://github.com/angular/angular.js/commit/57b626a673b7530399d3377dfe770165bec35f8a))
<add>- **ngModelController:** allow $overrideModelOptions to set updateOn
<add> ([55516d](https://github.com/angular/angular.js/commit/55516da2dfc7c5798dce24e9fa930c5ac90c900c),
<add> [#16351](https://github.com/angular/angular.js/issues/16351),
<add> [#16364](https://github.com/angular/angular.js/issues/16364))
<add>
<add>
<add>## New Features
<add>- **$parse:** add a hidden interface to retrieve an expression's AST
<add> ([f33d95](https://github.com/angular/angular.js/commit/f33d95cfcff6fd0270f92a142df8794cca2013ad),
<add> [#16253](https://github.com/angular/angular.js/issues/16253),
<add> [#16260](https://github.com/angular/angular.js/issues/16260))
<add>
<ide> <a name="1.6.7"></a>
<ide> # 1.6.7 imperial-backstroke (2017-11-24)
<ide> | 1 |
Javascript | Javascript | add $locatonchange[begin|completed] event | 92a2e1807657c69e1372106b0727675a30f4cbd7 | <ide><path>src/bootstrap/bootstrap-prettify.js
<ide> directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location',
<ide> $provide.value('$anchorScroll', angular.noop);
<ide> $provide.value('$browser', $browser);
<ide> $provide.provider('$location', function() {
<del> this.$get = function() { return $location; };
<add> this.$get = ['$rootScope', function($rootScope) {
<add> docsRootScope.$on('$locationChangeSuccess', function(event, oldUrl, newUrl) {
<add> $rootScope.$broadcast('$locationChangeSuccess', oldUrl, newUrl);
<add> });
<add> return $location;
<add> }];
<ide> this.html5Mode = angular.noop;
<ide> });
<ide> $provide.decorator('$defer', ['$rootScope', '$delegate', function($rootScope, $delegate) {
<ide><path>src/ng/location.js
<ide> function locationGetterSetter(property, preprocess) {
<ide> * @requires $rootElement
<ide> *
<ide> * @description
<del> * The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
<add> * The $location service parses the URL in the browser address bar (based on the
<add> * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
<add> * available to your application. Changes to the URL in the address bar are reflected into
<add> * $location service and changes to $location are reflected into the browser address bar.
<ide> *
<ide> * **The $location service:**
<ide> *
<ide> function locationGetterSetter(property, preprocess) {
<ide> * - Clicks on a link.
<ide> * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
<ide> *
<del> * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location}
<add> * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
<add> * Services: Using $location}
<ide> */
<ide>
<ide> /**
<ide> function $LocationProvider(){
<ide>
<ide> this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
<ide> function( $rootScope, $browser, $sniffer, $rootElement) {
<del> var currentUrl,
<add> var $location,
<ide> basePath = $browser.baseHref() || '/',
<ide> pathPrefix = pathPrefixFromBase(basePath),
<del> initUrl = $browser.url();
<add> initUrl = $browser.url(),
<add> absUrlPrefix;
<ide>
<ide> if (html5Mode) {
<ide> if ($sniffer.history) {
<del> currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix);
<add> $location = new LocationUrl(
<add> convertToHtml5Url(initUrl, basePath, hashPrefix),
<add> pathPrefix);
<ide> } else {
<del> currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix),
<del> hashPrefix);
<add> $location = new LocationHashbangUrl(
<add> convertToHashbangUrl(initUrl, basePath, hashPrefix),
<add> hashPrefix);
<ide> }
<add> } else {
<add> $location = new LocationHashbangUrl(initUrl, hashPrefix);
<add> }
<ide>
<del> // link rewriting
<del> var u = currentUrl,
<del> absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix;
<add> // link rewriting
<add> absUrlPrefix = composeProtocolHostPort(
<add> $location.protocol(), $location.host(), $location.port()) + pathPrefix;
<ide>
<del> $rootElement.bind('click', function(event) {
<del> // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
<del> // currently we open nice url link and redirect then
<add> $rootElement.bind('click', function(event) {
<add> // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
<add> // currently we open nice url link and redirect then
<ide>
<del> if (event.ctrlKey || event.metaKey || event.which == 2) return;
<add> if (event.ctrlKey || event.metaKey || event.which == 2) return;
<ide>
<del> var elm = jqLite(event.target);
<add> var elm = jqLite(event.target);
<ide>
<del> // traverse the DOM up to find first A tag
<del> while (elm.length && lowercase(elm[0].nodeName) !== 'a') {
<del> elm = elm.parent();
<del> }
<add> // traverse the DOM up to find first A tag
<add> while (elm.length && lowercase(elm[0].nodeName) !== 'a') {
<add> elm = elm.parent();
<add> }
<ide>
<del> var absHref = elm.prop('href');
<add> var absHref = elm.prop('href');
<ide>
<del> if (!absHref ||
<del> elm.attr('target') ||
<del> absHref.indexOf(absUrlPrefix) !== 0) { // link to different domain or base path
<del> return;
<del> }
<add> if (!absHref ||
<add> elm.attr('target') ||
<add> absHref.indexOf(absUrlPrefix) !== 0) { // link to different domain or base path
<add> return;
<add> }
<add>
<add> // update location with href without the prefix
<add> $location.url(absHref.substr(absUrlPrefix.length));
<add> $rootScope.$apply();
<add> event.preventDefault();
<add> // hack to work around FF6 bug 684208 when scenario runner clicks on links
<add> window.angular['ff-684208-preventDefault'] = true;
<add> });
<ide>
<del> // update location with href without the prefix
<del> currentUrl.url(absHref.substr(absUrlPrefix.length));
<del> $rootScope.$apply();
<del> event.preventDefault();
<del> // hack to work around FF6 bug 684208 when scenario runner clicks on links
<del> window.angular['ff-684208-preventDefault'] = true;
<del> });
<del> } else {
<del> currentUrl = new LocationHashbangUrl(initUrl, hashPrefix);
<del> }
<ide>
<ide> // rewrite hashbang url <> html5 url
<del> if (currentUrl.absUrl() != initUrl) {
<del> $browser.url(currentUrl.absUrl(), true);
<add> if ($location.absUrl() != initUrl) {
<add> $browser.url($location.absUrl(), true);
<ide> }
<ide>
<ide> // update $location when $browser url changes
<ide> $browser.onUrlChange(function(newUrl) {
<del> if (currentUrl.absUrl() != newUrl) {
<add> if ($location.absUrl() != newUrl) {
<ide> $rootScope.$evalAsync(function() {
<del> currentUrl.$$parse(newUrl);
<add> var oldUrl = $location.absUrl();
<add>
<add> $location.$$parse(newUrl);
<add> afterLocationChange(oldUrl);
<ide> });
<ide> if (!$rootScope.$$phase) $rootScope.$digest();
<ide> }
<ide> function $LocationProvider(){
<ide> // update browser
<ide> var changeCounter = 0;
<ide> $rootScope.$watch(function $locationWatch() {
<del> if ($browser.url() != currentUrl.absUrl()) {
<add> var oldUrl = $browser.url();
<add>
<add> if (!changeCounter || oldUrl != $location.absUrl()) {
<ide> changeCounter++;
<ide> $rootScope.$evalAsync(function() {
<del> $browser.url(currentUrl.absUrl(), currentUrl.$$replace);
<del> currentUrl.$$replace = false;
<add> if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
<add> defaultPrevented) {
<add> $location.$$parse(oldUrl);
<add> } else {
<add> $browser.url($location.absUrl(), $location.$$replace);
<add> $location.$$replace = false;
<add> afterLocationChange(oldUrl);
<add> }
<ide> });
<ide> }
<ide>
<ide> return changeCounter;
<ide> });
<ide>
<del> return currentUrl;
<add> return $location;
<add>
<add> function afterLocationChange(oldUrl) {
<add> $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
<add> }
<ide> }];
<ide> }
<ide><path>src/ng/route.js
<ide> function $RouteProvider(){
<ide> */
<ide>
<ide> var matcher = switchRouteMatcher,
<del> dirty = 0,
<ide> forceReload = false,
<ide> $route = {
<ide> routes: routes,
<ide> function $RouteProvider(){
<ide> * creates new scope, reinstantiates the controller.
<ide> */
<ide> reload: function() {
<del> dirty++;
<ide> forceReload = true;
<add> $rootScope.$evalAsync(updateRoute);
<ide> }
<ide> };
<ide>
<del> $rootScope.$watch(function() { return dirty + $location.url(); }, updateRoute);
<add> $rootScope.$on('$locationChangeSuccess', updateRoute);
<ide>
<ide> return $route;
<ide>
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> it('should not rewrite when history disabled', function() {
<del> configureService('#new', false);
<del> inject(
<del> initBrowser(),
<del> initLocation(),
<del> function($browser) {
<del> browserTrigger(link, 'click');
<del> expectNoRewrite($browser);
<del> }
<del> );
<del> });
<del>
<del>
<ide> it('should not rewrite full url links do different domain', function() {
<ide> configureService('http://www.dot.abc/a?b=c', true);
<ide> inject(
<ide> describe('$location', function() {
<ide> });
<ide> }
<ide> });
<add>
<add>
<add> describe('location cancellation', function() {
<add> it('should fire $before/afterLocationChange event', inject(function($location, $browser, $rootScope, $log) {
<add> expect($browser.url()).toEqual('http://server/');
<add>
<add> $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
<add> $log.info('before', newUrl, oldUrl, $browser.url());
<add> });
<add> $rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
<add> $log.info('after', newUrl, oldUrl, $browser.url());
<add> });
<add>
<add> expect($location.url()).toEqual('');
<add> $location.url('/somePath');
<add> expect($location.url()).toEqual('/somePath');
<add> expect($browser.url()).toEqual('http://server/');
<add> expect($log.info.logs).toEqual([]);
<add>
<add> $rootScope.$apply();
<add>
<add> expect($log.info.logs.shift()).
<add> toEqual(['before', 'http://server/#/somePath', 'http://server/', 'http://server/']);
<add> expect($log.info.logs.shift()).
<add> toEqual(['after', 'http://server/#/somePath', 'http://server/', 'http://server/#/somePath']);
<add> expect($location.url()).toEqual('/somePath');
<add> expect($browser.url()).toEqual('http://server/#/somePath');
<add> }));
<add>
<add>
<add> it('should allow $locationChangeStart event cancellation', inject(function($location, $browser, $rootScope, $log) {
<add> expect($browser.url()).toEqual('http://server/');
<add> expect($location.url()).toEqual('');
<add>
<add> $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
<add> $log.info('before', newUrl, oldUrl, $browser.url());
<add> event.preventDefault();
<add> });
<add> $rootScope.$on('$locationChangeCompleted', function(event, newUrl, oldUrl) {
<add> throw Error('location should have been canceled');
<add> });
<add>
<add> expect($location.url()).toEqual('');
<add> $location.url('/somePath');
<add> expect($location.url()).toEqual('/somePath');
<add> expect($browser.url()).toEqual('http://server/');
<add> expect($log.info.logs).toEqual([]);
<add>
<add> $rootScope.$apply();
<add>
<add> expect($log.info.logs.shift()).
<add> toEqual(['before', 'http://server/#/somePath', 'http://server/', 'http://server/']);
<add> expect($log.info.logs[1]).toBeUndefined();
<add> expect($location.url()).toEqual('');
<add> expect($browser.url()).toEqual('http://server/');
<add> }));
<add>
<add> it ('should fire $locationChangeCompleted event when change from browser location bar',
<add> inject(function($log, $location, $browser, $rootScope) {
<add> $rootScope.$apply(); // clear initial $locationChangeStart
<add>
<add> expect($browser.url()).toEqual('http://server/');
<add> expect($location.url()).toEqual('');
<add>
<add> $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
<add> throw Error('there is no before when user enters URL directly to browser');
<add> });
<add> $rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
<add> $log.info('after', newUrl, oldUrl);
<add> });
<add>
<add>
<add> $browser.url('http://server/#/somePath');
<add> $browser.poll();
<add>
<add> expect($log.info.logs.shift()).
<add> toEqual(['after', 'http://server/#/somePath', 'http://server/']);
<add> })
<add> );
<add>
<add>
<add> it('should listen on click events on href and prevent browser default in hasbang mode', function() {
<add> module(function() {
<add> return function($rootElement, $compile, $rootScope) {
<add> $rootElement.html('<a href="http://server/#/somePath">link</a>');
<add> $compile($rootElement)($rootScope);
<add> jqLite(document.body).append($rootElement);
<add> }
<add> });
<add>
<add> inject(function($location, $rootScope, $browser, $rootElement) {
<add> var log = '',
<add> link = $rootElement.find('a');
<add>
<add>
<add> $rootScope.$on('$locationChangeStart', function(event) {
<add> event.preventDefault();
<add> log += '$locationChangeStart';
<add> });
<add> $rootScope.$on('$locationChangeCompleted', function() {
<add> throw new Error('after cancellation in hashbang mode');
<add> });
<add>
<add> browserTrigger(link, 'click');
<add>
<add> expect(log).toEqual('$locationChangeStart');
<add> expect($browser.url()).toEqual('http://server/');
<add>
<add> dealoc($rootElement);
<add> });
<add> });
<add>
<add>
<add> it('should listen on click events on href and prevent browser default in html5 mode', function() {
<add> module(function($locationProvider) {
<add> $locationProvider.html5Mode(true);
<add> return function($rootElement, $compile, $rootScope) {
<add> $rootElement.html('<a href="http://server/somePath">link</a>');
<add> $compile($rootElement)($rootScope);
<add> jqLite(document.body).append($rootElement);
<add> }
<add> });
<add>
<add> inject(function($location, $rootScope, $browser, $rootElement) {
<add> var log = '',
<add> link = $rootElement.find('a');
<add>
<add> $rootScope.$on('$locationChangeStart', function(event) {
<add> event.preventDefault();
<add> log += '$locationChangeStart';
<add> });
<add> $rootScope.$on('$locationChangeCompleted', function() {
<add> throw new Error('after cancalation in html5 mode');
<add> });
<add>
<add> browserTrigger(link, 'click');
<add>
<add> expect(log).toEqual('$locationChangeStart');
<add> expect($browser.url()).toEqual('http://server/');
<add>
<add> dealoc($rootElement);
<add> });
<add> });
<add> });
<ide> });
<ide><path>test/ng/routeSpec.js
<ide> describe('$route', function() {
<ide> });
<ide>
<ide>
<add> it('should not change route when location is canceled', function() {
<add> module(function($routeProvider) {
<add> $routeProvider.when('/somePath', {template: 'some path'});
<add> });
<add> inject(function($route, $location, $rootScope, $log) {
<add> $rootScope.$on('$locationChangeStart', function(event) {
<add> $log.info('$locationChangeStart');
<add> event.preventDefault();
<add> });
<add>
<add> $rootScope.$on('$beforeRouteChange', function(event) {
<add> throw new Error('Should not get here');
<add> });
<add>
<add> $location.path('/somePath');
<add> $rootScope.$digest();
<add>
<add> expect($log.info.logs.shift()).toEqual(['$locationChangeStart']);
<add> });
<add> });
<add>
<add>
<ide> it('should match a route that contains special chars in the path', function() {
<ide> module(function($routeProvider) {
<ide> $routeProvider.when('/$test.23/foo(bar)/:baz', {templateUrl: 'test.html'});
<ide> describe('$route', function() {
<ide> });
<ide> inject(function($route, $location, $rootScope) {
<ide> var replace;
<del> $rootScope.$watch(function() {
<del> if (isUndefined(replace)) replace = $location.$$replace;
<add>
<add> $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
<add> if (oldUrl == 'http://server/#/foo/id3/eId') {
<add> replace = $location.$$replace;
<add> }
<ide> });
<ide>
<ide> $location.path('/foo/id3/eId'); | 5 |
Text | Text | fix broken links in faq | 028c47dc5ce8de8a5513d984969f1f4231be6cc6 | <ide><path>docs/templates/getting-started/faq.md
<ide> - [How can I use HDF5 inputs with Keras?](#how-can-i-use-hdf5-inputs-with-keras)
<ide> - [Where is the Keras configuration file stored?](#where-is-the-keras-configuration-file-stored)
<ide> - [How can I obtain reproducible results using Keras during development?](#how-can-i-obtain-reproducible-results-using-keras-during-development)
<del>- [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-HDF5-or-h5py-to-save-my-models-in-Keras)
<add>- [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras)
<ide>
<ide> ---
<ide>
<ide> You can then use `keras.models.load_model(filepath)` to reinstantiate your model
<ide> `load_model` will also take care of compiling the model using the saved training configuration
<ide> (unless the model was never compiled in the first place).
<ide>
<del>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-HDF5-or-h5py-to-save-my-models-in-Keras) for instructions on how to install `h5py`.
<add>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras) for instructions on how to install `h5py`.
<ide>
<ide> Example:
<ide>
<ide> If you need to load weights into a *different* architecture (with some layers in
<ide> model.load_weights('my_model_weights.h5', by_name=True)
<ide> ```
<ide>
<del>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-HDF5-or-h5py-to-save-my-models-in-Keras) for instructions on how to install `h5py`.
<add>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras) for instructions on how to install `h5py`.
<ide>
<ide> For example:
<ide>
<ide> with h5py.File('input/file.hdf5', 'r') as f:
<ide> model.predict(x_data)
<ide> ```
<ide>
<del>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-HDF5-or-h5py-to-save-my-models-in-Keras) for instructions on how to install `h5py`.
<add>Please also see [How can I install HDF5 or h5py to save my models in Keras?](#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras) for instructions on how to install `h5py`.
<ide>
<ide> ---
<ide> | 1 |
Python | Python | remove users of `numpy.compat.open_latin1` | b2f8b7c5e0f66f48398d830cebd499a60a2e7120 | <ide><path>numpy/distutils/fcompiler/__init__.py
<ide> import sys
<ide> import re
<ide>
<del>from numpy.compat import open_latin1
<del>
<ide> from distutils.sysconfig import get_python_lib
<ide> from distutils.fancy_getopt import FancyGetopt
<ide> from distutils.errors import DistutilsModuleError, \
<ide> def is_free_format(file):
<ide> # f90 allows both fixed and free format, assuming fixed unless
<ide> # signs of free format are detected.
<ide> result = 0
<del> f = open_latin1(file, 'r')
<del> line = f.readline()
<del> n = 10000 # the number of non-comment lines to scan for hints
<del> if _has_f_header(line):
<del> n = 0
<del> elif _has_f90_header(line):
<del> n = 0
<del> result = 1
<del> while n>0 and line:
<del> line = line.rstrip()
<del> if line and line[0]!='!':
<del> n -= 1
<del> if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&':
<del> result = 1
<del> break
<add> with open(file, encoding='latin1') as f:
<ide> line = f.readline()
<del> f.close()
<add> n = 10000 # the number of non-comment lines to scan for hints
<add> if _has_f_header(line):
<add> n = 0
<add> elif _has_f90_header(line):
<add> n = 0
<add> result = 1
<add> while n>0 and line:
<add> line = line.rstrip()
<add> if line and line[0]!='!':
<add> n -= 1
<add> if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&':
<add> result = 1
<add> break
<add> line = f.readline()
<ide> return result
<ide>
<ide> def has_f90_header(src):
<del> f = open_latin1(src, 'r')
<del> line = f.readline()
<del> f.close()
<add> with open(src, encoding='latin1') as f:
<add> line = f.readline()
<ide> return _has_f90_header(line) or _has_fix_header(line)
<ide>
<ide> _f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P<fcname>\w+)\s*\)\s*=\s*(?P<fflags>.*)', re.I)
<ide> def get_f77flags(src):
<ide> Return a dictionary {<fcompiler type>:<f77 flags>}.
<ide> """
<ide> flags = {}
<del> f = open_latin1(src, 'r')
<del> i = 0
<del> for line in f:
<del> i += 1
<del> if i>20: break
<del> m = _f77flags_re.match(line)
<del> if not m: continue
<del> fcname = m.group('fcname').strip()
<del> fflags = m.group('fflags').strip()
<del> flags[fcname] = split_quoted(fflags)
<del> f.close()
<add> with open(src, encoding='latin1') as f:
<add> i = 0
<add> for line in f:
<add> i += 1
<add> if i>20: break
<add> m = _f77flags_re.match(line)
<add> if not m: continue
<add> fcname = m.group('fcname').strip()
<add> fflags = m.group('fflags').strip()
<add> flags[fcname] = split_quoted(fflags)
<ide> return flags
<ide>
<ide> # TODO: implement get_f90flags and use it in _compile similarly to get_f77flags | 1 |
PHP | PHP | adjust event facade comment for ide hint | 18b1b8946cc71cc074ea2733ff2054fb21d1dcb5 | <ide><path>src/Illuminate/Support/Facades/Event.php
<ide> * @method static void flush(string $event)
<ide> * @method static void forget(string $event)
<ide> * @method static void forgetPushed()
<del> * @method static void listen(string|array $events, \Closure|string $listener = null)
<add> * @method static void listen(\Closure|string|array $events, \Closure|string $listener = null)
<ide> * @method static void push(string $event, array $payload = [])
<ide> * @method static void subscribe(object|string $subscriber)
<ide> * | 1 |
Ruby | Ruby | return sql literal nodes | c59f91e4af4dad29c94d6cd969a45d9288746a0b | <ide><path>lib/arel/select_manager.rb
<ide> def join_sql
<ide> end
<ide>
<ide> def order_clauses
<del> Visitors::OrderClauses.new(@engine).accept @head
<add> Visitors::OrderClauses.new(@engine).accept(@head).map { |x|
<add> Nodes::SqlLiteral.new x
<add> }
<ide> end
<ide>
<ide> def joins manager
<ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Time o; quote(o) end
<ide>
<ide> DISPATCH = {}
<ide> def visit object
<del> #send "visit_#{object.class.name.gsub('::', '_')}", object
<del> send DISPATCH[object.class], object
<add> send "visit_#{object.class.name.gsub('::', '_')}", object
<add> #send DISPATCH[object.class], object
<ide> end
<ide>
<ide> private_instance_methods(false).each do |method| | 2 |
Text | Text | add link anchor [ci skip] | 02d2fdb123f38c11b26a190f62a9f1c28c7619ab | <ide><path>website/docs/usage/training.md
<ide> The default score weights are defined by each pipeline component via the
<ide> components are weighted equally. If a score weight is set to `null`, it will be
<ide> excluded from the logs and the score won't be weighted.
<ide>
<del><Accordion title="Understanding the training output and score types" spaced>
<add><Accordion title="Understanding the training output and score types" spaced id="score-types">
<ide>
<ide> | Name | Description |
<ide> | -------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | 1 |
Javascript | Javascript | remove useless return statement | ee2d69b9015beae3b381f5bc9c83a0ec74fd3887 | <ide><path>lib/Compiler.js
<ide> class Compiler {
<ide> this.cache.beginIdle();
<ide> this.running = false;
<ide>
<del> let callbackRst;
<del> if (callback !== undefined) {
<del> callbackRst = callback(err, stats);
<del> }
<add> if (callback !== undefined) callback(err, stats);
<ide> this.hooks.afterDone.call(stats);
<del> return callbackRst;
<ide> };
<ide>
<ide> const startTime = Date.now(); | 1 |
Javascript | Javascript | adopt setfrommatrixcolumn in orbit controls | b1c0f302710766d0ac7610891c6809e80cddbc24 | <ide><path>examples/js/controls/OrbitControls.js
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide>
<ide> return function panLeft( distance, objectMatrix ) {
<ide>
<del> var te = objectMatrix.elements;
<del>
<del> // get X column of objectMatrix
<del> v.set( te[ 0 ], te[ 1 ], te[ 2 ] );
<del>
<add> v.setFromMatrixColumn( 0, objectMatrix ); // get X column of objectMatrix
<ide> v.multiplyScalar( - distance );
<ide>
<ide> panOffset.add( v );
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide>
<ide> return function panUp( distance, objectMatrix ) {
<ide>
<del> var te = objectMatrix.elements;
<del>
<del> // get Y column of objectMatrix
<del> v.set( te[ 4 ], te[ 5 ], te[ 6 ] );
<del>
<add> v.setFromMatrixColumn( 1, objectMatrix ); // get Y column of objectMatrix
<ide> v.multiplyScalar( distance );
<ide>
<ide> panOffset.add( v ); | 1 |
PHP | PHP | fix controller comment | 4bfcb064bfc8468d0f47fc270838d1ae7a4c5872 | <ide><path>application/controllers/home.php
<ide> class Home_Controller extends Controller {
<ide> | application "routes.php" file. Laravel is smart enough to find this
<ide> | controller and call the default method, which is "get_index".
<ide> |
<del> | Just like routes, controllers are also RESTful by default. Each function
<add> | Just like routes, controllers are also RESTful by default. Each method
<ide> | is prefixed with the HTTP verb it responds to, allowing you to quickly
<ide> | build beautiful RESTful applications.
<ide> | | 1 |
Ruby | Ruby | reapply extensions when using except and only | 96b9fc44000e5f40ba463ff0e893db8c4fd33b85 | <ide><path>activerecord/lib/active_record/relation/spawn_methods.rb
<ide> def except(*skips)
<ide> result.send(:"#{method}_value=", send(:"#{method}_value"))
<ide> end
<ide>
<add> # Apply scope extension modules
<add> result.send(:apply_modules, extensions)
<add>
<ide> result
<ide> end
<ide>
<ide> def only(*onlies)
<ide> result.send(:"#{method}_value=", send(:"#{method}_value"))
<ide> end
<ide>
<add> # Apply scope extension modules
<add> result.send(:apply_modules, extensions)
<add>
<ide> result
<ide> end
<ide>
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_except
<ide> assert_equal Post.all, all_posts.all
<ide> end
<ide>
<add> def test_extensions_with_except
<add> assert_equal 2, Topic.named_extension.order(:author_name).except(:order).two
<add> end
<add>
<ide> def test_only
<ide> relation = Post.where(:author_id => 1).order('id ASC').limit(1)
<ide> assert_equal [posts(:welcome)], relation.all
<ide> def test_only
<ide> assert_equal Post.limit(1).all.first, all_posts.first
<ide> end
<ide>
<add> def test_extensions_with_only
<add> assert_equal 2, Topic.named_extension.order(:author_name).only(:order).two
<add> end
<add>
<ide> def test_anonymous_extension
<ide> relation = Post.where(:author_id => 1).order('id ASC').extending do
<ide> def author | 2 |
PHP | PHP | remove trailing newline from hot url | 23f259aeacabf532041a926e7c262789760063ea | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function mix($path, $manifestDirectory = '')
<ide> }
<ide>
<ide> if (file_exists(public_path($manifestDirectory.'/hot'))) {
<del> $url = file_get_contents(public_path($manifestDirectory.'/hot'));
<add> $url = rtrim(file_get_contents(public_path($manifestDirectory.'/hot')));
<ide>
<ide> if (Str::startsWith($url, ['http://', 'https://'])) {
<ide> return new HtmlString(Str::after($url, ':').$path); | 1 |
Python | Python | restore missing import | 5798ce765184f320c70c5130a515984b17c10f52 | <ide><path>numpy/core/multiarray.py
<ide> from . import overrides
<ide> from . import _multiarray_umath
<ide> from ._multiarray_umath import * # noqa: F403
<add># These imports are needed for backward compatibility,
<add># do not change them. issue gh-15518
<add># _get_ndarray_c_version is semi-public, on purpose not added to __all__
<ide> from ._multiarray_umath import (
<ide> _fastCopyAndTranspose, _flagdict, _insert, _reconstruct, _vec_string,
<ide> _ARRAY_API, _monotonicity, _get_ndarray_c_version
<ide><path>numpy/core/umath.py
<ide>
<ide> from . import _multiarray_umath
<ide> from ._multiarray_umath import * # noqa: F403
<del>from ._multiarray_umath import _UFUNC_API, _add_newdoc_ufunc
<add># These imports are needed for backward compatibility,
<add># do not change them. issue gh-11862
<add># _ones_like is semi-public, on purpose not added to __all__
<add>from ._multiarray_umath import _UFUNC_API, _add_newdoc_ufunc, _ones_like
<ide>
<ide> __all__ = [
<ide> '_UFUNC_API', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', | 2 |
Ruby | Ruby | remove unnecessary reader | e20dd73df42d63b206d221e2258cc6dc7b1e6068 | <ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> class << self
<ide> self.valid_options = [:class_name, :foreign_key, :validate]
<ide> self.extensions = []
<ide>
<del> attr_reader :model, :name, :scope, :options, :reflection
<add> attr_reader :model, :name, :scope, :options
<ide>
<ide> def self.build(*args, &block)
<ide> new(*args, &block).build
<ide> def build
<ide> validate_options
<ide> define_accessors
<ide> configure_dependency if options[:dependent]
<del> @reflection = model.create_reflection(macro, name, scope, options, model)
<add> reflection = model.create_reflection(macro, name, scope, options, model)
<ide> Association.extensions.each do |extension|
<del> extension.build @model, @reflection
<add> extension.build @model, reflection
<ide> end
<del> @reflection
<add> reflection
<ide> end
<ide>
<ide> def macro | 1 |
Mixed | Text | require action_view to fix missing constant | 47860b62b3c9a915c00fd379b705c545d4c6eb0d | <ide><path>actionpack/CHANGELOG.md
<add>* Properly require `action_view` in `AbstractController::Rendering` to prevent
<add> uninitialized constant error for `ENCODING_FLAG`.
<add>
<add> *Philipe Fatio*
<add>
<ide> * Do not discard query parameters that form a hash with the same root key as
<ide> the `wrapper_key` for a request using `wrap_parameters`.
<ide>
<ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> require 'active_support/concern'
<ide> require 'active_support/core_ext/class/attribute'
<add>require 'action_view'
<ide> require 'action_view/view_paths'
<ide> require 'set'
<ide> | 2 |
Javascript | Javascript | add getproperties method to sc.observable | 68e5dadca88bb0b4cf9bcdd00d3ac970ea28be39 | <ide><path>packages/sproutcore-runtime/lib/mixins/observable.js
<ide> SC.Observable = SC.Mixin.create(/** @scope SC.Observable.prototype */ {
<ide> get: function(keyName) {
<ide> return get(this, keyName);
<ide> },
<add>
<add> /**
<add> To get multiple properties at once, call getProperties
<add> with an Array:
<add>
<add> record.getProperties(['firstName', 'lastName', 'zipCode']);
<add>
<add> @param {Array} array of keys to get
<add> @returns {Hash}
<add> */
<add> getProperties: function(keyNames) {
<add> var ret = {};
<add> for(var i = 0; i < keyNames.length; i++) {
<add> ret[keyNames[i]] = get(this, keyNames[i]);
<add> }
<add> return ret;
<add> },
<ide>
<ide> /**
<ide> Sets the key equal to value.
<ide><path>packages/sproutcore-runtime/tests/mixins/observable_test.js
<add>// ==========================================================================
<add>// Project: SproutCore Runtime
<add>// Copyright: ©2011 Strobe Inc. and contributors.
<add>// License: Licensed under MIT license (see license.js)
<add>// ==========================================================================
<add>
<add>module('mixins/observable');
<add>
<add>test('should be able to use getProperties to get a POJO of provided keys', function() {
<add> var obj = SC.Object.create({
<add> firstName: "Steve",
<add> lastName: "Jobs",
<add> zipCode: 94301
<add> });
<add>
<add> var pojo = obj.getProperties("firstName lastName".w());
<add> equals("Steve", pojo.firstName);
<add> equals("Jobs", pojo.lastName);
<add>});
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | fix typo in flatlist docs | 22da6f2f3f7bab852f05921d32d8425123e70b55 | <ide><path>Libraries/CustomComponents/Lists/FlatList.js
<ide> type OptionalProps<ItemT> = {
<ide> */
<ide> keyExtractor: (item: ItemT, index: number) => string,
<ide> /**
<del> * Multiple columns can only be rendered with `horizontal={false}`` and will zig-zag like a
<add> * Multiple columns can only be rendered with `horizontal={false}` and will zig-zag like a
<ide> * `flexWrap` layout. Items should all be the same height - masonry layouts are not supported.
<ide> */
<ide> numColumns: number, | 1 |
Python | Python | use api dict for ufunc as well | 6ec24a68d20f092fe6ec67b66f3078c43b8b873b | <ide><path>numpy/core/code_generators/generate_ufunc_api.py
<ide> import os
<ide> import genapi
<add>import genapi2
<add>
<add>import numpy_api
<add>
<add>from genapi2 import \
<add> TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi
<ide>
<ide> h_template = r"""
<ide> #ifdef _UMATHMODULE
<ide> #endif
<ide> #endif
<ide>
<del>#define PyUFunc_Type (*(PyTypeObject *)PyUFunc_API[0])
<del>
<ide> %s
<ide>
<ide> static int
<ide> */
<ide>
<ide> void *PyUFunc_API[] = {
<del> (void *) &PyUFunc_Type,
<ide> %s
<ide> };
<ide> """
<ide> def do_generate_api(targets, sources):
<ide> c_file = targets[1]
<ide> doc_file = targets[2]
<ide>
<del> ufunc_api_list = genapi.get_api_functions('UFUNC_API', sources[0])
<add> ufunc_api_index = genapi2.merge_api_dicts((
<add> numpy_api.ufunc_funcs_api,
<add> numpy_api.ufunc_types_api))
<add> genapi2.check_api_dict(ufunc_api_index)
<ide>
<del> # API fixes for __arrayobject_api.h
<add> ufunc_api_list = genapi2.get_api_functions('UFUNC_API', numpy_api.ufunc_funcs_api)
<ide>
<del> fixed = 1
<del> nummulti = len(ufunc_api_list)
<del> numtotal = fixed + nummulti
<add> # Create dict name -> *Api instance
<add> ufunc_api_dict = {}
<add> api_name = 'PyUFunc_API'
<add> for f in ufunc_api_list:
<add> name = f.name
<add> index = ufunc_api_index[name]
<add> ufunc_api_dict[name] = FunctionApi(f.name, index, f.return_type,
<add> f.args, api_name)
<ide>
<add> for name, index in numpy_api.ufunc_types_api.items():
<add> ufunc_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name)
<add>
<add> # set up object API
<ide> module_list = []
<ide> extension_list = []
<ide> init_list = []
<ide>
<del> # set up object API
<del> genapi.add_api_list(fixed, 'PyUFunc_API', ufunc_api_list,
<del> module_list, extension_list, init_list)
<add> for name, index in genapi2.order_dict(ufunc_api_index):
<add> api_item = ufunc_api_dict[name]
<add> extension_list.append(api_item.define_from_array_api_string())
<add> init_list.append(api_item.array_api_define())
<add> module_list.append(api_item.internal_define())
<ide>
<ide> # Write to header
<ide> fid = open(header_file, 'w')
<ide> def do_generate_api(targets, sources):
<ide>
<ide> # Write to c-code
<ide> fid = open(c_file, 'w')
<del> s = c_template % '\n'.join(init_list)
<add> s = c_template % ',\n'.join(init_list)
<ide> fid.write(s)
<ide> fid.close()
<ide> | 1 |
Text | Text | fix typo in readme.md | 6bb522bab43702eb3a7e21218ae303a021518fef | <ide><path>README.md
<ide> or availability of the Node.js application or its system for which the attacker
<ide> does not already have the capability.
<ide>
<ide> To illustrate the point, here are some examples of past issues and what the
<del>Security Reponse Team thinks of them. When in doubt, however, please do send
<add>Security Response Team thinks of them. When in doubt, however, please do send
<ide> us a report nonetheless.
<ide>
<ide> | 1 |
Python | Python | implement a fasttext example | 46d5b197e022815c2074fbc94ca324d31d470dd0 | <ide><path>examples/imdb_fasttext.py
<add>'''This example demonstrates the use of fasttext for text classification
<add>
<add>Based on Joulin et al's paper:
<add>
<add>Bags of Tricks for Efficient Text Classification
<add>https://arxiv.org/abs/1607.01759
<add>
<add>Can achieve accuracy around 88% after 5 epochs in 70s.
<add>
<add>'''
<add>
<add>from __future__ import print_function
<add>import numpy as np
<add>np.random.seed(1337) # for reproducibility
<add>
<add>from keras.preprocessing import sequence
<add>from keras.models import Sequential
<add>from keras.layers import Dense, Activation, Flatten
<add>from keras.layers import Embedding
<add>from keras.layers import AveragePooling1D
<add>from keras.datasets import imdb
<add>from keras import backend as K
<add>
<add>
<add># set parameters:
<add>max_features = 20000
<add>maxlen = 400
<add>batch_size = 32
<add>embedding_dims = 20
<add>nb_epoch = 5
<add>
<add>print('Loading data...')
<add>(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=max_features)
<add>print(len(X_train), 'train sequences')
<add>print(len(X_test), 'test sequences')
<add>
<add>print('Pad sequences (samples x time)')
<add>X_train = sequence.pad_sequences(X_train, maxlen=maxlen)
<add>X_test = sequence.pad_sequences(X_test, maxlen=maxlen)
<add>print('X_train shape:', X_train.shape)
<add>print('X_test shape:', X_test.shape)
<add>
<add>print('Build model...')
<add>model = Sequential()
<add>
<add># we start off with an efficient embedding layer which maps
<add># our vocab indices into embedding_dims dimensions
<add>model.add(Embedding(max_features,
<add> embedding_dims,
<add> input_length=maxlen))
<add>
<add># we add a AveragePooling1D, which will average the embeddings
<add># of all words in the document
<add>model.add(AveragePooling1D(pool_length=model.output_shape[1]))
<add>
<add># We flatten the output of the AveragePooling1D layer
<add>model.add(Flatten())
<add>
<add># We project onto a single unit output layer, and squash it with a sigmoid:
<add>model.add(Dense(1, activation = 'sigmoid'))
<add>
<add>model.compile(loss='binary_crossentropy',
<add> optimizer='adam',
<add> metrics=['accuracy'])
<add>
<add>model.fit(X_train, y_train,
<add> batch_size=batch_size,
<add> nb_epoch=nb_epoch,
<add> validation_data=(X_test, y_test)) | 1 |
PHP | PHP | add curly brackets | 04c4b03c15123ebc9a1f943ce965a29c87e5fa3d | <ide><path>src/Illuminate/Cookie/Middleware/EncryptCookies.php
<ide> protected function decryptArray(array $cookie)
<ide> $decrypted = array();
<ide>
<ide> foreach ($cookie as $key => $value)
<add> {
<ide> $decrypted[$key] = $this->encrypter->decrypt($value);
<add> }
<ide>
<ide> return $decrypted;
<ide> } | 1 |
Javascript | Javascript | fix eslint error | a9c771a8aceef9339217b35d9f569355b2f8b142 | <ide><path>lib/Template.js
<ide> const stringifyIdSortPredicate = (a, b) => {
<ide>
<ide> /**
<ide> * @param {Module} module the module to compare against
<del> * @return {boolean} return true if module.id is equal to type "number"
<add> * @returns {boolean} return true if module.id is equal to type "number"
<ide> */
<ide> const moduleIdIsNumber = module => {
<ide> return typeof module.id === "number";
<ide> class Template {
<ide> /**
<ide> *
<ide> * @param {Module[]} modules a collection of modules to get array bounds for
<del> * @return {[number, number] | false} returns the upper and lower array bounds
<add> * @returns {[number, number] | false} returns the upper and lower array bounds
<ide> * or false if not every module has a number based id
<ide> */
<ide> static getModulesArrayBounds(modules) { | 1 |
Text | Text | fix typo in options for render [ci skip] | 4069282d74f350a3b3814928c8c428be78dca06b | <ide><path>guides/source/layouts_and_rendering.md
<ide> TIP: `send_file` is often a faster and better option if a layout isn't required.
<ide>
<ide> #### Options for `render`
<ide>
<del>Calls to the `render` method generally accept five options:
<add>Calls to the `render` method generally accept six options:
<ide>
<ide> * `:content_type`
<ide> * `:layout` | 1 |
Go | Go | add fixme for the change detection | 804abddec155dedc42e99ad746f1cf1fdbfe0fed | <ide><path>fs/store.go
<ide> func (image *Image) Mount(root, rw string) (*Mountpoint, error) {
<ide> }
<ide>
<ide> // FIXME: Create tests for deletion
<add> // FIXME: move this part to change.go, maybe refactor
<add> // fs.Change() to avoid the fake mountpoint
<ide> // Retrieve the changeset from the parent and apply it to the container
<ide> // - Retrieve the changes
<ide> changes, err := image.store.Changes(&Mountpoint{ | 1 |
Python | Python | eliminate some resource warnings | 6c359e0f532d18a71895f035dd1326ca5d2d67f8 | <ide><path>tests/conftest.py
<ide> :license: BSD, see LICENSE for more details.
<ide> """
<ide> import flask
<add>import gc
<ide> import os
<ide> import sys
<ide> import pkgutil
<ide> def inner(name):
<ide> @pytest.yield_fixture(autouse=True)
<ide> def catch_deprecation_warnings(recwarn):
<ide> yield
<add> gc.collect()
<ide> assert not recwarn.list
<ide><path>tests/test_basic.py
<ide> def test_static_path_deprecated(recwarn):
<ide> app.testing = True
<ide> rv = app.test_client().get('/foo/index.html')
<ide> assert rv.status_code == 200
<add> rv.close()
<add>
<ide> with app.test_request_context():
<ide> assert flask.url_for('static', filename='index.html') == '/foo/index.html'
<ide>
<ide> def test_static_url_path():
<ide> app.testing = True
<ide> rv = app.test_client().get('/foo/index.html')
<ide> assert rv.status_code == 200
<add> rv.close()
<add>
<ide> with app.test_request_context():
<ide> assert flask.url_for('static', filename='index.html') == '/foo/index.html'
<ide>
<ide><path>tests/test_helpers.py
<ide> def test_send_file_object(self, recwarn):
<ide> app = flask.Flask(__name__)
<ide>
<ide> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')
<del> rv = flask.send_file(f)
<del> rv.direct_passthrough = False
<del> with app.open_resource('static/index.html') as f:
<del> assert rv.data == f.read()
<del> assert rv.mimetype == 'text/html'
<del> rv.close()
<add> with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:
<add> rv = flask.send_file(f)
<add> rv.direct_passthrough = False
<add> with app.open_resource('static/index.html') as f:
<add> assert rv.data == f.read()
<add> assert rv.mimetype == 'text/html'
<add> rv.close()
<ide>
<ide> # mimetypes + etag
<ide> recwarn.pop(DeprecationWarning)
<ide> def test_send_file_object(self, recwarn):
<ide> app.use_x_sendfile = True
<ide>
<ide> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'))
<del> rv = flask.send_file(f)
<del> assert rv.mimetype == 'text/html'
<del> assert 'x-sendfile' in rv.headers
<del> assert rv.headers['x-sendfile'] == \
<del> os.path.join(app.root_path, 'static/index.html')
<del> rv.close()
<add> with open(os.path.join(app.root_path, 'static/index.html')) as f:
<add> rv = flask.send_file(f)
<add> assert rv.mimetype == 'text/html'
<add> assert 'x-sendfile' in rv.headers
<add> assert rv.headers['x-sendfile'] == \
<add> os.path.join(app.root_path, 'static/index.html')
<add> rv.close()
<ide>
<ide> # mimetypes + etag
<ide> recwarn.pop(DeprecationWarning)
<ide> def __getattr__(self, name):
<ide> def test_attachment(self, recwarn):
<ide> app = flask.Flask(__name__)
<ide> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'))
<del> rv = flask.send_file(f, as_attachment=True)
<del> value, options = parse_options_header(rv.headers['Content-Disposition'])
<del> assert value == 'attachment'
<del> rv.close()
<add> with open(os.path.join(app.root_path, 'static/index.html')) as f:
<add> rv = flask.send_file(f, as_attachment=True)
<add> value, options = \
<add> parse_options_header(rv.headers['Content-Disposition'])
<add> assert value == 'attachment'
<add> rv.close()
<ide>
<ide> # mimetypes + etag
<ide> assert len(recwarn.list) == 2 | 3 |
Ruby | Ruby | get perl/ruby from homebrew_path | 3448335a14612bc7d3d426f79e3705b2bdad26cd | <ide><path>Library/Homebrew/system_config.rb
<ide> def describe_path(path)
<ide> end
<ide>
<ide> def describe_perl
<del> describe_path(which("perl"))
<add> describe_path(which("perl", ENV["HOMEBREW_PATH"]))
<ide> end
<ide>
<ide> def describe_python
<ide> def describe_python
<ide> end
<ide>
<ide> def describe_ruby
<del> ruby = which "ruby"
<add> ruby = which "ruby", ENV["HOMEBREW_PATH"]
<ide> return "N/A" if ruby.nil?
<ide> ruby_binary = Utils.popen_read ruby, "-rrbconfig", "-e", \
<ide> 'include RbConfig;print"#{CONFIG["bindir"]}/#{CONFIG["ruby_install_name"]}#{CONFIG["EXEEXT"]}"' | 1 |
Javascript | Javascript | move edits to src/package.js | ea284ebf6027b8ed038858fce2694c7af46130c0 | <ide><path>src/package.js
<ide> console.log(JSON.stringify({
<ide> },
<ide> "scripts": {
<ide> "test": "node_modules/.bin/vows; echo"
<del> }
<add> },
<add> "licenses": [
<add> {
<add> "type": "BSD",
<add> "url": "https://github.com/mbostock/d3/blob/master/LICENSE"
<add> }
<add> ]
<ide> }, null, 2)); | 1 |
Text | Text | add solution to arguments optional challenge | 03c603787f30713ba5662c2e5f8d897987ad99c7 | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional/index.md
<ide> It can be quite complicated to understand what needs to be done. There are alway
<ide>
<ide> ### Relevant Links
<ide>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array' target='_blank' rel='nofollow'>Arrays</a>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments' target='_blank' rel='nofollow'>arguments object</a>
<add>* [Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
<add>* [Typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
<add>* [Arguments Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
<ide>
<ide> ##  Hint: 1
<ide>
<ide> In the case that only one argument was passed, do not worry about how to prompt
<ide> // test here
<ide> addTogether(2,3);
<ide> ```
<del> <a href='https://repl.it/CLnz/0' target='_blank' rel='nofollow'>Run Code</a>
<ide>
<ide> ### Code Explanation:
<ide>
<ide> In the case that only one argument was passed, do not worry about how to prompt
<ide>
<ide> #### Relevant Links
<ide>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments' target='_blank' rel='nofollow'>arguments object</a>
<add>* [Typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
<add>* [Arguments Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
<ide>
<ide> ##  Intermediate Code Solution:
<ide> ```javascript
<del> function addTogether() {
<del> var args = new Array(arguments.length);
<del> //Storing the arguments in an array
<del> for(var i = 0; i < args.length; ++i) {
<del> args[i] = arguments[i];
<del> }
<del> //Check for the arguments length
<del> if(args.length == 2){
<del> //If there are two arguments,check for the type of both arguments
<del> //Use typeof to check the type of the argument(both should be numbers)
<del> if(typeof args[0] !== 'number' || typeof args[1] !=='number' ){
<del> return undefined;
<del> }
<del> return args[0]+args[1];
<del> }
<del> //When only one argument is provided
<del> if(args.length == 1){
<del> a= args[0];
<del> //Check the argument using typeof
<del> if(typeof a!=='number'){
<del> return undefined;
<del> }
<del> else{
<del> //Making use of closures
<del> return function(b){
<del> //Checking the second argument
<del> if(typeof b !=='number'){
<del> return undefined;
<del> }
<del> else
<del> return a+b;
<del> };
<del> }
<del> }
<del> }
<del>
<del> // test here
<del> addTogether(2,3);
<add>function addTogether(first, second) {
<add> if (typeof first !== 'number') {
<add> return undefined;
<add> }
<add> const sum = second => (typeof second === 'number' ? first + second : undefined);
<add> return typeof second === 'undefined' ? second => sum(second) : sum(second);
<add>}
<add>// test here
<add>addTogether(2,3);
<ide> ```
<del> <a href='https://repl.it/CLoA/0' target='_blank' rel='nofollow'>Run Code</a>
<ide>
<ide> ### Code Explanation:
<ide>
<del>* First store the arguments in an array by creating an array using the constructor method.
<del>* Adds each argument to the new array.
<del>* Then check for the length of the new array as we need to know if we have enough or not.
<del>* Check for the type of the arguments using `typeof` as they both should be numbers.
<del>* Returns undefined if any of them is not a number, or returns the sum of them if they are.
<del>* If there was only one argument, we still check the type after storing it in a new variable and returning a new function or undefined.
<add>* Return `undefined` if first argument is not a `number` or second argument is defined, but not a `number`.
<add>* Return sum of the arguments if both are provided otherwise return a sum function.
<ide>
<ide> #### Relevant Links
<ide>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments' target='_blank' rel='nofollow'>arguments object</a>
<add>* [Typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
<add>* [Arguments Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
<ide>
<ide> ##  Advanced Code Solution:
<ide> ```javascript
<ide> In the case that only one argument was passed, do not worry about how to prompt
<ide> // test here
<ide> addTogether(2,3);
<ide> ```
<del> <a href='https://repl.it/CLoB/0' target='_blank' rel='nofollow'>Run Code</a>
<ide>
<ide> ### Code Explanation:
<ide>
<ide> In the case that only one argument was passed, do not worry about how to prompt
<ide>
<ide> #### Relevant Links
<ide>
<del>* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>Array.prototype.reduce</a>
<del>* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-some/14304' target='_blank' rel='nofollow'>Array.prototype.some</a>
<del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from' target='_blank' rel='nofollow'>Array.from</a>
<add>* [Array.prototype.reduce](https://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299)
<add>* [Array.prototype.some](https://forum.freecodecamp.com/t/javascript-array-prototype-some/14304)
<add>* [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
<ide>
<ide>
<ide> ##  NOTES FOR CONTRIBUTIONS: | 1 |
Python | Python | convert property to @property | c458774c637c508f4b1e49ebaa2f85083579fa10 | <ide><path>numpy/core/getlimits.py
<ide> def __init__(self, int_type):
<ide> if self.kind not in 'iu':
<ide> raise ValueError("Invalid integer data type %r." % (self.kind,))
<ide>
<add> @property
<ide> def min(self):
<ide> """Minimum value of given dtype."""
<ide> if self.kind == 'u':
<ide> def min(self):
<ide> iinfo._min_vals[self.key] = val
<ide> return val
<ide>
<del> min = property(min)
<del>
<add> @property
<ide> def max(self):
<ide> """Maximum value of given dtype."""
<ide> try:
<ide> def max(self):
<ide> iinfo._max_vals[self.key] = val
<ide> return val
<ide>
<del> max = property(max)
<del>
<ide> def __str__(self):
<ide> """String representation."""
<ide> fmt = (
<ide><path>numpy/ma/core.py
<ide> def _get_mask(self):
<ide>
<ide> mask = property(fget=_get_mask, fset=__setmask__, doc="Mask")
<ide>
<del> def _get_recordmask(self):
<add> @property
<add> def recordmask(self):
<ide> """
<ide> Return the mask of the records.
<ide>
<ide> def _get_recordmask(self):
<ide> return _mask
<ide> return np.all(flatten_structured_array(_mask), axis=-1)
<ide>
<del> def _set_recordmask(self):
<add> @recordmask.setter
<add> def recordmask(self, mask):
<ide> """
<del> Return the mask of the records.
<del>
<del> A record is masked when all the fields are masked.
<add> Set the mask of the records.
<ide>
<ide> """
<ide> raise NotImplementedError("Coming soon: setting the mask per records!")
<ide>
<del> recordmask = property(fget=_get_recordmask)
<del>
<ide> def harden_mask(self):
<ide> """
<ide> Force the mask to hard.
<ide> def soften_mask(self):
<ide> self._hardmask = False
<ide> return self
<ide>
<del> hardmask = property(fget=lambda self: self._hardmask,
<del> doc="Hardness of the mask")
<add> @property
<add> def hardmask(self):
<add> """ Hardness of the mask """
<add> return self._hardmask
<ide>
<ide> def unshare_mask(self):
<ide> """
<ide> def unshare_mask(self):
<ide> self._sharedmask = False
<ide> return self
<ide>
<del> sharedmask = property(fget=lambda self: self._sharedmask,
<del> doc="Share status of the mask (read-only).")
<add> @property
<add> def sharedmask(self):
<add> """ Share status of the mask (read-only). """
<add> return self._sharedmask
<ide>
<ide> def shrink_mask(self):
<ide> """
<ide> def shrink_mask(self):
<ide> self._mask = _shrink_mask(self._mask)
<ide> return self
<ide>
<del> baseclass = property(fget=lambda self: self._baseclass,
<del> doc="Class of the underlying data (read-only).")
<add> @property
<add> def baseclass(self):
<add> """ Class of the underlying data (read-only). """
<add> return self._baseclass
<ide>
<ide> def _get_data(self):
<ide> """Return the current data, as a view of the original
<ide> def _get_data(self):
<ide> _data = property(fget=_get_data)
<ide> data = property(fget=_get_data)
<ide>
<del> def _get_flat(self):
<del> "Return a flat iterator."
<add> @property
<add> def flat(self):
<add> """ Return a flat iterator. """
<ide> return MaskedIterator(self)
<ide>
<del> def _set_flat(self, value):
<del> "Set a flattened version of self to value."
<add> @flat.setter
<add> def flat(self, value):
<add> """ Set a flattened version of self to value. """
<ide> y = self.ravel()
<ide> y[:] = value
<ide>
<del> flat = property(fget=_get_flat, fset=_set_flat,
<del> doc="Flat version of the array.")
<del>
<del> def get_fill_value(self):
<add> @property
<add> def fill_value(self):
<ide> """
<ide> Return the filling value of the masked array.
<ide>
<ide> def get_fill_value(self):
<ide> return self._fill_value[()]
<ide> return self._fill_value
<ide>
<del> def set_fill_value(self, value=None):
<add> @fill_value.setter
<add> def fill_value(self, value=None):
<ide> """
<ide> Set the filling value of the masked array.
<ide>
<ide> def set_fill_value(self, value=None):
<ide> # Don't overwrite the attribute, just fill it (for propagation)
<ide> _fill_value[()] = target
<ide>
<del> fill_value = property(fget=get_fill_value, fset=set_fill_value,
<del> doc="Filling value.")
<add> get_fill_value = fill_value.fget
<add> set_fill_value = fill_value.fset
<ide>
<ide> def filled(self, fill_value=None):
<ide> """
<ide> def __long__(self):
<ide> raise MaskError('Cannot convert masked element to a Python long.')
<ide> return long(self.item())
<ide>
<del>
<del> def get_imag(self):
<add> @property
<add> def imag(self):
<ide> """
<ide> Return the imaginary part of the masked array.
<ide>
<ide> def get_imag(self):
<ide> result.__setmask__(self._mask)
<ide> return result
<ide>
<del> imag = property(fget=get_imag, doc="Imaginary part.")
<add> get_imag = imag.fget
<ide>
<del> def get_real(self):
<add> @property
<add> def real(self):
<ide> """
<ide> Return the real part of the masked array.
<ide>
<ide> def get_real(self):
<ide> result = self._data.real.view(type(self))
<ide> result.__setmask__(self._mask)
<ide> return result
<del> real = property(fget=get_real, doc="Real part")
<add>
<add> get_real = real.fget
<ide>
<ide> def count(self, axis=None, keepdims=np._NoValue):
<ide> """
<ide> def take(self, indices, axis=None, out=None, mode='raise'):
<ide> repeat = _arraymethod('repeat')
<ide> squeeze = _arraymethod('squeeze')
<ide> swapaxes = _arraymethod('swapaxes')
<del> T = property(fget=lambda self: self.transpose())
<ide> transpose = _arraymethod('transpose')
<ide>
<add> @property
<add> def T(self):
<add> return self.transpose()
<add>
<ide> def tolist(self, fill_value=None):
<ide> """
<ide> Return the data portion of the masked array as a hierarchical Python list.
<ide> def __new__(self, data, mask=nomask, dtype=None, fill_value=None,
<ide> _data.fill_value = fill_value
<ide> return _data
<ide>
<del> def _get_data(self):
<add> @property
<add> def _data(self):
<ide> # Make sure that the _data part is a np.void
<ide> return super(mvoid, self)._data[()]
<ide>
<del> _data = property(fget=_get_data)
<del>
<ide> def __getitem__(self, indx):
<ide> """
<ide> Get the index.
<ide><path>numpy/ma/mrecords.py
<ide> def __array_finalize__(self, obj):
<ide> _dict['_baseclass'] = recarray
<ide> return
<ide>
<del> def _getdata(self):
<add> @property
<add> def _data(self):
<ide> """
<ide> Returns the data as a recarray.
<ide>
<ide> """
<ide> return ndarray.view(self, recarray)
<ide>
<del> _data = property(fget=_getdata)
<del>
<del> def _getfieldmask(self):
<add> @property
<add> def _fieldmask(self):
<ide> """
<ide> Alias to mask.
<ide>
<ide> """
<ide> return self._mask
<ide>
<del> _fieldmask = property(fget=_getfieldmask)
<del>
<ide> def __len__(self):
<ide> """
<ide> Returns the length
<ide><path>numpy/ma/tests/test_subclassing.py
<ide> def __new__(cls, data, info={}, mask=nomask):
<ide> _data.info = subarr.info
<ide> return _data
<ide>
<del> def _get_series(self):
<add> @property
<add> def _series(self):
<ide> _view = self.view(MaskedArray)
<ide> _view._sharedmask = False
<ide> return _view
<del> _series = property(fget=_get_series)
<ide>
<ide> msubarray = MSubArray
<ide>
<ide><path>numpy/matrixlib/defmatrix.py
<ide> def ptp(self, axis=None, out=None):
<ide> """
<ide> return N.ndarray.ptp(self, axis, out)._align(axis)
<ide>
<del> def getI(self):
<add> @property
<add> def I(self):
<ide> """
<ide> Returns the (multiplicative) inverse of invertible `self`.
<ide>
<ide> def getI(self):
<ide> from numpy.dual import pinv as func
<ide> return asmatrix(func(self))
<ide>
<del> def getA(self):
<add> @property
<add> def A(self):
<ide> """
<ide> Return `self` as an `ndarray` object.
<ide>
<ide> def getA(self):
<ide> """
<ide> return self.__array__()
<ide>
<del> def getA1(self):
<add> @property
<add> def A1(self):
<ide> """
<ide> Return `self` as a flattened `ndarray`.
<ide>
<ide> def ravel(self, order='C'):
<ide> """
<ide> return N.ndarray.ravel(self, order=order)
<ide>
<del>
<del> def getT(self):
<add> @property
<add> def T(self):
<ide> """
<ide> Returns the transpose of the matrix.
<ide>
<ide> def getT(self):
<ide> """
<ide> return self.transpose()
<ide>
<del> def getH(self):
<add> @property
<add> def H(self):
<ide> """
<ide> Returns the (complex) conjugate transpose of `self`.
<ide>
<ide> def getH(self):
<ide> else:
<ide> return self.transpose()
<ide>
<del> T = property(getT, None)
<del> A = property(getA, None)
<del> A1 = property(getA1, None)
<del> H = property(getH, None)
<del> I = property(getI, None)
<add> # kept for compatibility
<add> getT = T.fget
<add> getA = A.fget
<add> getA1 = A1.fget
<add> getH = H.fget
<add> getI = I.fget
<ide>
<ide> def _from_string(str, gdict, ldict):
<ide> rows = str.split(';')
<ide><path>numpy/matrixlib/tests/test_masked_matrix.py
<ide> def __array_finalize__(self, obj):
<ide> MaskedArray.__array_finalize__(self, obj)
<ide> return
<ide>
<del> def _get_series(self):
<add> @property
<add> def _series(self):
<ide> _view = self.view(MaskedArray)
<ide> _view._sharedmask = False
<ide> return _view
<del> _series = property(fget=_get_series)
<ide>
<ide>
<ide> class TestMaskedMatrix(object):
<ide><path>tools/npy_tempita/_looper.py
<ide> def __repr__(self):
<ide> return '<loop pos=%r at %r>' % (
<ide> self.seq[self.pos], self.pos)
<ide>
<add> @property
<ide> def index(self):
<ide> return self.pos
<del> index = property(index)
<ide>
<add> @property
<ide> def number(self):
<ide> return self.pos + 1
<del> number = property(number)
<ide>
<add> @property
<ide> def item(self):
<ide> return self.seq[self.pos]
<del> item = property(item)
<ide>
<add> @property
<ide> def __next__(self):
<ide> try:
<ide> return self.seq[self.pos + 1]
<ide> except IndexError:
<ide> return None
<del> __next__ = property(__next__)
<ide>
<ide> if sys.version < "3":
<ide> next = __next__
<ide>
<add> @property
<ide> def previous(self):
<ide> if self.pos == 0:
<ide> return None
<ide> return self.seq[self.pos - 1]
<del> previous = property(previous)
<ide>
<add> @property
<ide> def odd(self):
<ide> return not self.pos % 2
<del> odd = property(odd)
<ide>
<add> @property
<ide> def even(self):
<ide> return self.pos % 2
<del> even = property(even)
<ide>
<add> @property
<ide> def first(self):
<ide> return self.pos == 0
<del> first = property(first)
<ide>
<add> @property
<ide> def last(self):
<ide> return self.pos == len(self.seq) - 1
<del> last = property(last)
<ide>
<add> @property
<ide> def length(self):
<ide> return len(self.seq)
<del> length = property(length)
<ide>
<ide> def first_group(self, getter=None):
<ide> """ | 7 |
Java | Java | add runtime hints for scheduling support | fd265a18c619b21f97f753871c6e1c32df65ba32 | <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java
<ide> import java.lang.annotation.Target;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import org.springframework.aot.hint.annotation.Reflective;
<ide> import org.springframework.scheduling.config.ScheduledTaskRegistrar;
<ide>
<ide> /**
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @Repeatable(Schedules.class)
<add>@Reflective
<ide> public @interface Scheduled {
<ide>
<ide> /**
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java
<ide> import org.springframework.context.ApplicationContextAware;
<ide> import org.springframework.context.ApplicationListener;
<ide> import org.springframework.context.EmbeddedValueResolverAware;
<add>import org.springframework.context.annotation.ImportRuntimeHints;
<ide> import org.springframework.context.event.ContextRefreshedEvent;
<ide> import org.springframework.core.MethodIntrospector;
<ide> import org.springframework.core.Ordered;
<ide> * @see org.springframework.scheduling.config.ScheduledTaskRegistrar
<ide> * @see AsyncAnnotationBeanPostProcessor
<ide> */
<add>@ImportRuntimeHints(ScheduledAnnotationRuntimeHintsRegistrar.class)
<ide> public class ScheduledAnnotationBeanPostProcessor
<ide> implements ScheduledTaskHolder, MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor,
<ide> Ordered, EmbeddedValueResolverAware, BeanNameAware, BeanFactoryAware, ApplicationContextAware,
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationRuntimeHintsRegistrar.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.scheduling.annotation;
<add>
<add>import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsRegistrar;
<add>import org.springframework.aot.hint.support.RuntimeHintsUtils;
<add>
<add>/**
<add> * {@link RuntimeHintsRegistrar} implementation that registers runtime hints for
<add> * {@link Scheduled} annotation.
<add> *
<add> * @author Sebastien Deleuze
<add> * @since 6.0
<add> */
<add>public class ScheduledAnnotationRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
<add>
<add> @Override
<add> public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
<add> RuntimeHintsUtils.registerAnnotation(hints, Scheduled.class);
<add> RuntimeHintsUtils.registerAnnotation(hints, Schedules.class);
<add> }
<add>}
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/Schedules.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<add>import org.springframework.aot.hint.annotation.Reflective;
<add>
<ide> /**
<ide> * Container annotation that aggregates several {@link Scheduled} annotations.
<ide> *
<ide> @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<add>@Reflective
<ide> public @interface Schedules {
<ide>
<ide> Scheduled[] value(); | 4 |
Java | Java | improve javadoc of xobserver types. | f7a28703bd533ad235114e27e86cc7ac06ee9dfb | <ide><path>src/main/java/io/reactivex/CompletableObserver.java
<ide> import io.reactivex.disposables.Disposable;
<ide>
<ide> /**
<del> * Represents the subscription API callbacks when subscribing to a Completable instance.
<add> * Provides a mechanism for receiving push-based notification of a valueless completion or an error.
<add> * <p>
<add> * When a {@code CompletableObserver} is subscribed to a {@link CompletableSource} through the {@link CompletableSource#subscribe(CompletableObserver)} method,
<add> * the {@code CompletableSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<add> * disposing the sequence at any time. A well-behaved
<add> * {@code CompletableSource} will call a {@code CompletableObserver}'s {@link #onError(Throwable)}
<add> * or {@link #onComplete()} method exactly once as they are considered mutually exclusive <strong>terminal signals</strong>.
<add> * <p>
<add> * Calling the {@code CompletableObserver}'s method must happen in a serialized fashion, that is, they must not
<add> * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must
<add> * adhere to the following protocol:
<add> * <p>
<add> * <pre><code> onSubscribe (onError | onComplete)?</code></pre>
<add> * <p>
<add> * Subscribing a {@code CompletableObserver} to multiple {@code CompletableSource}s is not recommended. If such reuse
<add> * happens, it is the duty of the {@code CompletableObserver} implementation to be ready to receive multiple calls to
<add> * its methods and ensure proper concurrent behavior of its business logic.
<add> * <p>
<add> * Calling {@link #onSubscribe(Disposable)} or {@link #onError(Throwable)} with a
<add> * {@code null} argument is forbidden.
<add> * <p>
<add> * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases:
<add> * <ul>
<add> * <li>If the argument is {@code null}, the methods can throw a {@code NullPointerException}.
<add> * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no
<add> * need to check for nulls in flows assembled from standard sources and intermediate operators.
<add> * </li>
<add> * <li>If there is a fatal error (such as {@code VirtualMachineError}).</li>
<add> * </ul>
<add> * @since 2.0
<ide> */
<ide> public interface CompletableObserver {
<ide> /**
<ide><path>src/main/java/io/reactivex/MaybeObserver.java
<ide> import io.reactivex.disposables.Disposable;
<ide>
<ide> /**
<del> * Provides a mechanism for receiving push-based notifications.
<add> * Provides a mechanism for receiving push-based notification of a single value, an error or completion without any value.
<ide> * <p>
<del> * After a MaybeObserver calls a {@link Maybe}'s {@link Maybe#subscribe subscribe} method,
<del> * first the Maybe calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<del> * cancelling the sequence at any time, then the
<del> * {@code Maybe} calls only one of the MaybeObserver's {@link #onSuccess}, {@link #onError} or
<del> * {@link #onComplete} methods to provide notifications.
<del> *
<add> * When a {@code MaybeObserver} is subscribed to a {@link MaybeSource} through the {@link MaybeSource#subscribe(MaybeObserver)} method,
<add> * the {@code MaybeSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<add> * disposing the sequence at any time. A well-behaved
<add> * {@code MaybeSource} will call a {@code MaybeObserver}'s {@link #onSuccess(Object)}, {@link #onError(Throwable)}
<add> * or {@link #onComplete()} method exactly once as they are considered mutually exclusive <strong>terminal signals</strong>.
<add> * <p>
<add> * Calling the {@code MaybeObserver}'s method must happen in a serialized fashion, that is, they must not
<add> * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must
<add> * adhere to the following protocol:
<add> * <p>
<add> * <pre><code> onSubscribe (onSuccess | onError | onComplete)?</code></pre>
<add> * <p>
<add> * Note that unlike with the {@code Observable} protocol, {@link #onComplete()} is not called after the success item has been
<add> * signalled via {@link #onSuccess(Object)}.
<add> * <p>
<add> * Subscribing a {@code MaybeObserver} to multiple {@code MaybeSource}s is not recommended. If such reuse
<add> * happens, it is the duty of the {@code MaybeObserver} implementation to be ready to receive multiple calls to
<add> * its methods and ensure proper concurrent behavior of its business logic.
<add> * <p>
<add> * Calling {@link #onSubscribe(Disposable)}, {@link #onSuccess(Object)} or {@link #onError(Throwable)} with a
<add> * {@code null} argument is forbidden.
<add> * <p>
<add> * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases:
<add> * <ul>
<add> * <li>If the argument is {@code null}, the methods can throw a {@code NullPointerException}.
<add> * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no
<add> * need to check for nulls in flows assembled from standard sources and intermediate operators.
<add> * </li>
<add> * <li>If there is a fatal error (such as {@code VirtualMachineError}).</li>
<add> * </ul>
<ide> * @see <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation: Observable</a>
<ide> * @param <T>
<ide> * the type of item the MaybeObserver expects to observe
<ide><path>src/main/java/io/reactivex/Observer.java
<ide> /**
<ide> * Provides a mechanism for receiving push-based notifications.
<ide> * <p>
<del> * After an Observer calls an {@link Observable}'s {@link Observable#subscribe subscribe} method,
<del> * first the Observable calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<del> * cancelling the sequence at any time, then the
<del> * {@code Observable} may call the Observer's {@link #onNext} method any number of times
<add> * When an {@code Observer} is subscribed to an {@link ObservableSource} through the {@link ObservableSource#subscribe(Observer)} method,
<add> * the {@code ObservableSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<add> * disposing the sequence at any time, then the
<add> * {@code ObservableSource} may call the Observer's {@link #onNext} method any number of times
<ide> * to provide notifications. A well-behaved
<del> * {@code Observable} will call an Observer's {@link #onComplete} method exactly once or the Observer's
<add> * {@code ObservableSource} will call an {@code Observer}'s {@link #onComplete} method exactly once or the {@code Observer}'s
<ide> * {@link #onError} method exactly once.
<del> *
<add> * <p>
<add> * Calling the {@code Observer}'s method must happen in a serialized fashion, that is, they must not
<add> * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must
<add> * adhere to the following protocol:
<add> * <p>
<add> * <pre><code> onSubscribe onNext* (onError | onComplete)?</code></pre>
<add> * <p>
<add> * Subscribing an {@code Observer} to multiple {@code ObservableSource}s is not recommended. If such reuse
<add> * happens, it is the duty of the {@code Observer} implementation to be ready to receive multiple calls to
<add> * its methods and ensure proper concurrent behavior of its business logic.
<add> * <p>
<add> * Calling {@link #onSubscribe(Disposable)}, {@link #onNext(Object)} or {@link #onError(Throwable)} with a
<add> * {@code null} argument is forbidden.
<add> * <p>
<add> * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases
<add> * (see <a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a> of the Reactive Streams specification):
<add> * <ul>
<add> * <li>If the argument is {@code null}, the methods can throw a {@code NullPointerException}.
<add> * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no
<add> * need to check for nulls in flows assembled from standard sources and intermediate operators.
<add> * </li>
<add> * <li>If there is a fatal error (such as {@code VirtualMachineError}).</li>
<add> * </ul>
<add> * <p>
<add> * Violating Rule 2.13 results in undefined flow behavior. Generally, the following can happen:
<add> * <ul>
<add> * <li>An upstream operator turns it into an {@link #onError} call.</li>
<add> * <li>If the flow is synchronous, the {@link ObservableSource#subscribe(Observer)} throws instead of returning normally.</li>
<add> * <li>If the flow is asynchronous, the exception propagates up to the component ({@link Scheduler} or {@link java.util.concurrent.Executor})
<add> * providing the asynchronous boundary the code is running and either routes the exception to the global
<add> * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} handler or the current thread's
<add> * {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.</li>
<add> * </ul>
<add> * From the {@code Observable}'s perspective, an {@code Observer} is the end consumer thus it is the {@code Observer}'s
<add> * responsibility to handle the error case and signal it "further down". This means unreliable code in the {@code onXXX}
<add> * methods should be wrapped into `try-catch`es, specifically in {@link #onError(Throwable)} or {@link #onComplete()}, and handled there
<add> * (for example, by logging it or presenting the user with an error dialog). However, if the error would be thrown from
<add> * {@link #onNext(Object)}, <a href="https://github.com/reactive-streams/reactive-streams-jvm#2.13">Rule 2.13</a> mandates
<add> * the implementation calls {@link Disposable#dispose()} and signals the exception in a way that is adequate to the target context,
<add> * for example, by calling {@link #onError(Throwable)} on the same {@code Observer} instance.
<add> * <p>
<add> * If, for some reason, the {@code Observer} won't follow Rule 2.13, the {@link Observable#safeSubscribe(Observer)} can wrap it
<add> * with the necessary safeguards and route exceptions thrown from {@code onNext} into {@code onError} and route exceptions thrown
<add> * from {@code onError} and {@code onComplete} into the global error handler via {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)}.
<ide> * @see <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation: Observable</a>
<ide> * @param <T>
<ide> * the type of item the Observer expects to observe
<ide><path>src/main/java/io/reactivex/SingleObserver.java
<ide> import io.reactivex.disposables.Disposable;
<ide>
<ide> /**
<del> * Provides a mechanism for receiving push-based notifications.
<add> * Provides a mechanism for receiving push-based notification of a single value or an error.
<ide> * <p>
<del> * After a SingleObserver calls a {@link Single}'s {@link Single#subscribe subscribe} method,
<del> * first the Single calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<del> * cancelling the sequence at any time, then the
<del> * {@code Single} calls only one of the SingleObserver {@link #onSuccess} and {@link #onError} methods to provide
<del> * notifications.
<del> *
<add> * When a {@code SingleObserver} is subscribed to a {@link SingleSource} through the {@link SingleSource#subscribe(SingleObserver)} method,
<add> * the {@code SingleSource} calls {@link #onSubscribe(Disposable)} with a {@link Disposable} that allows
<add> * disposing the sequence at any time. A well-behaved
<add> * {@code SingleSource} will call a {@code SingleObserver}'s {@link #onSuccess(Object)} method exactly once or the {@code SingleObserver}'s
<add> * {@link #onError} method exactly once as they are considered mutually exclusive <strong>terminal signals</strong>.
<add> * <p>
<add> * Calling the {@code SingleObserver}'s method must happen in a serialized fashion, that is, they must not
<add> * be invoked concurrently by multiple threads in an overlapping fashion and the invocation pattern must
<add> * adhere to the following protocol:
<add> * <p>
<add> * <pre><code> onSubscribe (onSuccess | onError)?</code></pre>
<add> * <p>
<add> * Subscribing a {@code SingleObserver} to multiple {@code SingleSource}s is not recommended. If such reuse
<add> * happens, it is the duty of the {@code SingleObserver} implementation to be ready to receive multiple calls to
<add> * its methods and ensure proper concurrent behavior of its business logic.
<add> * <p>
<add> * Calling {@link #onSubscribe(Disposable)}, {@link #onSuccess(Object)} or {@link #onError(Throwable)} with a
<add> * {@code null} argument is forbidden.
<add> * <p>
<add> * The implementations of the {@code onXXX} methods should avoid throwing runtime exceptions other than the following cases:
<add> * <ul>
<add> * <li>If the argument is {@code null}, the methods can throw a {@code NullPointerException}.
<add> * Note though that RxJava prevents {@code null}s to enter into the flow and thus there is generally no
<add> * need to check for nulls in flows assembled from standard sources and intermediate operators.
<add> * </li>
<add> * <li>If there is a fatal error (such as {@code VirtualMachineError}).</li>
<add> * </ul>
<ide> * @see <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation: Observable</a>
<ide> * @param <T>
<ide> * the type of item the SingleObserver expects to observe | 4 |
Python | Python | update ukrainian create_lemmatizer kwargs | e367864e59ed366adb8f1b416f91828c05eac3a0 | <ide><path>spacy/lang/uk/__init__.py
<ide> class UkrainianDefaults(Language.Defaults):
<ide> stop_words = STOP_WORDS
<ide>
<ide> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<add> def create_lemmatizer(cls, nlp=None, **kwargs):
<ide> return UkrainianLemmatizer()
<ide>
<ide> | 1 |
PHP | PHP | add a withcallback method | 87c4e23d2d48d0a487432bb9a91e45b8de75dec9 | <ide><path>src/Illuminate/Http/JsonResponse.php
<ide> public function __construct($data = null, $status = 200, $headers = [], $options
<ide> parent::__construct($data, $status, $headers);
<ide> }
<ide>
<add> /**
<add> * Sets the JSONP callback.
<add> *
<add> * @param string|null $callback
<add> * @return $this
<add> *
<add> * @throws \InvalidArgumentException
<add> */
<add> public function withCallback($callback = null)
<add> {
<add> return $this->setCallback($callback);
<add> }
<add>
<ide> /**
<ide> * Get the json_decoded data from the response.
<ide> * | 1 |
PHP | PHP | fix bug in fluent class | 10ee41f3b3306d5b29c05937f9b2086b538269d2 | <ide><path>laravel/fluent.php
<ide> public function __construct($attributes = array())
<ide> */
<ide> public function get($attribute, $default = null)
<ide> {
<del> return array_get($attributes, $attribute, $default);
<add> return array_get($this->attributes, $attribute, $default);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | eliminate nested conditional | a1e7d7177f713c3d3bed79e5723849875cd0df2f | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def prefix
<ide> elsif File.executable? "#{V4_BUNDLE_PATH}/Contents/Developer/usr/bin/make"
<ide> # fallback for broken Xcode 4.3 installs
<ide> Pathname.new("#{V4_BUNDLE_PATH}/Contents/Developer")
<del> else
<del> path = bundle_path
<del>
<del> unless path.nil?
<del> path += "Contents/Developer"
<del> path if File.executable? "#{path}/usr/bin/make"
<del> end
<add> elsif (path = bundle_path)
<add> path += "Contents/Developer"
<add> path if File.executable? "#{path}/usr/bin/make"
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | fix cs error | 855c4d114b0ac42169b1cb6237f9dcaefc5f4408 | <ide><path>src/Auth/BaseAuthenticate.php
<ide> public function passwordHasher()
<ide> }
<ide>
<ide> $passwordHasher = $this->_config['passwordHasher'];
<add>
<ide> return $this->_passwordHasher = PasswordHasherFactory::build($passwordHasher);
<ide> }
<ide>
<ide><path>src/Auth/BasicAuthenticate.php
<ide> public function getUser(Request $request)
<ide> if (!is_string($username) || $username === '' || !is_string($pass) || $pass === '') {
<ide> return false;
<ide> }
<add>
<ide> return $this->_findUser($username, $pass);
<ide> }
<ide>
<ide> public function unauthenticated(Request $request, Response $response)
<ide> public function loginHeaders(Request $request)
<ide> {
<ide> $realm = $this->config('realm') ?: $request->env('SERVER_NAME');
<add>
<ide> return sprintf('WWW-Authenticate: Basic realm="%s"', $realm);
<ide> }
<ide> }
<ide><path>src/Auth/ControllerAuthorize.php
<ide> public function controller(Controller $controller = null)
<ide> }
<ide> $this->_Controller = $controller;
<ide> }
<add>
<ide> return $this->_Controller;
<ide> }
<ide>
<ide><path>src/Auth/DigestAuthenticate.php
<ide> public function getUser(Request $request)
<ide> if ($digest['response'] === $hash) {
<ide> return $user;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _getDigest(Request $request)
<ide> if (empty($digest)) {
<ide> return false;
<ide> }
<add>
<ide> return $this->parseAuthData($digest);
<ide> }
<ide>
<ide> public function parseAuthData($digest)
<ide> if (empty($req)) {
<ide> return $keys;
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function loginHeaders(Request $request)
<ide> foreach ($options as $k => $v) {
<ide> $opts[] = sprintf('%s="%s"', $k, $v);
<ide> }
<add>
<ide> return 'WWW-Authenticate: Digest ' . implode(',', $opts);
<ide> }
<ide> }
<ide><path>src/Auth/FallbackPasswordHasher.php
<ide> public function check($password, $hashedPassword)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Auth/FormAuthenticate.php
<ide> protected function _checkFields(Request $request, array $fields)
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function authenticate(Request $request, Response $response)
<ide> if (!$this->_checkFields($request, $fields)) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_findUser(
<ide> $request->data[$fields['username']],
<ide> $request->data[$fields['password']]
<ide><path>src/Auth/Storage/MemoryStorage.php
<ide> public function redirectUrl($url = null)
<ide>
<ide> if ($url === false) {
<ide> $this->_redirectUrl = null;
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>src/Auth/Storage/SessionStorage.php
<ide> public function read()
<ide> }
<ide>
<ide> $this->_user = $this->_session->read($this->_config['key']) ?: false;
<add>
<ide> return $this->_user;
<ide> }
<ide>
<ide> public function redirectUrl($url = null)
<ide>
<ide> if ($url === false) {
<ide> $this->_session->delete($this->_config['redirect']);
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>src/Cache/Cache.php
<ide> public static function engine($config)
<ide> }
<ide>
<ide> static::_buildEngine($config);
<add>
<ide> return $registry->{$config};
<ide> }
<ide>
<ide> public static function write($key, $value, $config = 'default')
<ide> E_USER_WARNING
<ide> );
<ide> }
<add>
<ide> return $success;
<ide> }
<ide>
<ide> public static function writeMany($data, $config = 'default')
<ide> ));
<ide> }
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public static function writeMany($data, $config = 'default')
<ide> public static function read($key, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->read($key);
<ide> }
<ide>
<ide> public static function read($key, $config = 'default')
<ide> public static function readMany($keys, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->readMany($keys);
<ide> }
<ide>
<ide> public static function decrement($key, $offset = 1, $config = 'default')
<ide> public static function delete($key, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->delete($key);
<ide> }
<ide>
<ide> public static function delete($key, $config = 'default')
<ide> public static function deleteMany($keys, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->deleteMany($keys);
<ide> }
<ide>
<ide> public static function deleteMany($keys, $config = 'default')
<ide> public static function clear($check = false, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->clear($check);
<ide> }
<ide>
<ide> public static function clearAll($check = false)
<ide> public static function clearGroup($group, $config = 'default')
<ide> {
<ide> $engine = static::engine($config);
<add>
<ide> return $engine->clearGroup($group);
<ide> }
<ide>
<ide> public static function remember($key, $callable, $config = 'default')
<ide> }
<ide> $results = call_user_func($callable);
<ide> self::write($key, $results, $config);
<add>
<ide> return $results;
<ide> }
<ide>
<ide> public static function add($key, $value, $config = 'default')
<ide> if (is_resource($value)) {
<ide> return false;
<ide> }
<add>
<ide> return $engine->add($key, $value);
<ide> }
<ide> }
<ide><path>src/Cache/CacheEngine.php
<ide> public function writeMany($data)
<ide> foreach ($data as $key => $value) {
<ide> $return[$key] = $this->write($key, $value);
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function readMany($keys)
<ide> foreach ($keys as $key) {
<ide> $return[$key] = $this->read($key);
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function deleteMany($keys)
<ide> foreach ($keys as $key) {
<ide> $return[$key] = $this->delete($key);
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function add($key, $value)
<ide> if ($cachedValue === false) {
<ide> return $this->write($key, $value);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function key($key)
<ide> }
<ide>
<ide> $key = preg_replace('/[\s]+/', '_', strtolower(trim(str_replace([DIRECTORY_SEPARATOR, '/', '.'], '_', strval($key)))));
<add>
<ide> return $prefix . $key;
<ide> }
<ide>
<ide><path>src/Cache/CacheRegistry.php
<ide> protected function _resolveClassName($class)
<ide> if (is_object($class)) {
<ide> return $class;
<ide> }
<add>
<ide> return App::className($class, 'Cache/Engine', 'Engine');
<ide> }
<ide>
<ide> protected function _create($class, $alias, $config)
<ide> if ($config['probability'] && time() % $config['probability'] === 0) {
<ide> $instance->gc();
<ide> }
<add>
<ide> return $instance;
<ide> }
<ide>
<ide><path>src/Cache/Engine/ApcEngine.php
<ide> public function init(array $config = [])
<ide> }
<ide>
<ide> parent::init($config);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function write($key, $value)
<ide> $expires = time() + $duration;
<ide> }
<ide> apcu_store($key . '_expires', $expires, $duration);
<add>
<ide> return apcu_store($key, $value, $duration);
<ide> }
<ide>
<ide> public function read($key)
<ide> if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime)) {
<ide> return false;
<ide> }
<add>
<ide> return apcu_fetch($key);
<ide> }
<ide>
<ide> public function clear($check)
<ide> APC_ITER_NONE
<ide> );
<ide> apcu_delete($iterator);
<add>
<ide> return true;
<ide> }
<ide> $cache = apcu_cache_info();
<ide> public function clear($check)
<ide> apcu_delete($key['info']);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function add($key, $value)
<ide> $expires = time() + $duration;
<ide> }
<ide> apcu_add($key . '_expires', $expires, $duration);
<add>
<ide> return apcu_add($key, $value, $duration);
<ide> }
<ide>
<ide> public function groups()
<ide> foreach ($this->_config['groups'] as $i => $group) {
<ide> $result[] = $group . $groups[$i];
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function groups()
<ide> public function clearGroup($group)
<ide> {
<ide> apcu_inc($this->_config['prefix'] . $group, 1, $success);
<add>
<ide> return $success;
<ide> }
<ide> }
<ide><path>src/Cache/Engine/FileEngine.php
<ide> public function init(array $config = [])
<ide> if (!empty($this->_groupPrefix)) {
<ide> $this->_groupPrefix = str_replace('_', DIRECTORY_SEPARATOR, $this->_groupPrefix);
<ide> }
<add>
<ide> return $this->_active();
<ide> }
<ide>
<ide> public function read($key)
<ide> if ($this->_config['lock']) {
<ide> $this->_File->flock(LOCK_UN);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function read($key)
<ide> }
<ide> $data = unserialize((string)$data);
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public function clear($check)
<ide> $cleared[] = $path;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _setKey($key, $createKey = false)
<ide> $this->_File = $path->openFile('c+');
<ide> } catch (Exception $e) {
<ide> trigger_error($e->getMessage(), E_USER_WARNING);
<add>
<ide> return false;
<ide> }
<ide> unset($path);
<ide> protected function _setKey($key, $createKey = false)
<ide> ), E_USER_WARNING);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _active()
<ide> '%s is not writable',
<ide> $this->_config['path']
<ide> ), E_USER_WARNING);
<add>
<ide> return false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function key($key)
<ide> '_',
<ide> strval($key)
<ide> ));
<add>
<ide> return $key;
<ide> }
<ide>
<ide> public function clearGroup($group)
<ide> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> protected function _parseServerString($server)
<ide> $host = substr($server, 0, $position);
<ide> $port = substr($server, $position + 1);
<ide> }
<add>
<ide> return [$host, (int)$port];
<ide> }
<ide>
<ide> public function writeMany($data)
<ide> foreach (array_keys($data) as $key) {
<ide> $return[$key] = $success;
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function readMany($keys)
<ide> $return[$key] = array_key_exists($this->_key($key), $values) ?
<ide> $values[$this->_key($key)] : false;
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function deleteMany($keys)
<ide> foreach ($keys as $key) {
<ide> $return[$key] = $success;
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function add($key, $value)
<ide> }
<ide>
<ide> $key = $this->_key($key);
<add>
<ide> return $this->_Memcached->add($key, $value, $duration);
<ide> }
<ide>
<ide><path>src/Cache/Engine/RedisEngine.php
<ide> public function init(array $config = [])
<ide> }
<ide>
<ide> parent::init($config);
<add>
<ide> return $this->_connect();
<ide> }
<ide>
<ide> protected function _connect()
<ide> if ($return) {
<ide> $return = $this->_Redis->select($this->_config['database']);
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function read($key)
<ide> if ($value !== false && is_string($value)) {
<ide> return unserialize($value);
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> public function add($key, $value)
<ide> if ($this->_Redis->setnx($key, $value)) {
<ide> return $this->_Redis->setex($key, $duration, $value);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function groups()
<ide> }
<ide> $result[] = $group . $value;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Cache/Engine/WincacheEngine.php
<ide> public function init(array $config = [])
<ide> }
<ide>
<ide> parent::init($config);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function write($key, $value)
<ide> $key => $value
<ide> ];
<ide> $result = wincache_ucache_set($data, null, $duration);
<add>
<ide> return empty($result);
<ide> }
<ide>
<ide> public function read($key)
<ide> if ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime) {
<ide> return false;
<ide> }
<add>
<ide> return wincache_ucache_get($key);
<ide> }
<ide>
<ide> public function clear($check)
<ide> wincache_ucache_delete($key['key_name']);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function groups()
<ide> foreach ($this->_config['groups'] as $i => $group) {
<ide> $result[] = $group . $groups[$i];
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function clearGroup($group)
<ide> {
<ide> $success = null;
<ide> wincache_ucache_inc($this->_config['prefix'] . $group, 1, $success);
<add>
<ide> return $success;
<ide> }
<ide> }
<ide><path>src/Cache/Engine/XcacheEngine.php
<ide> public function init(array $config = [])
<ide> }
<ide>
<ide> parent::init($config);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function write($key, $value)
<ide> $duration = $this->_config['duration'];
<ide> $expires = time() + $duration;
<ide> xcache_set($key . '_expires', $expires, $duration);
<add>
<ide> return xcache_set($key, $value, $duration);
<ide> }
<ide>
<ide> public function read($key)
<ide> if (is_string($value) && !is_numeric($value)) {
<ide> $value = unserialize($value);
<ide> }
<add>
<ide> return $value;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function clear($check)
<ide> xcache_clear_cache(XC_TYPE_VAR, $i);
<ide> }
<ide> $this->_auth(true);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function groups()
<ide> }
<ide> $result[] = $group . $value;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Collection/CollectionTrait.php
<ide> public function each(callable $c)
<ide> foreach ($this->unwrap() as $k => $v) {
<ide> $c($v, $k);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function filter(callable $c = null)
<ide> return (bool)$v;
<ide> };
<ide> }
<add>
<ide> return new FilterIterator($this->unwrap(), $c);
<ide> }
<ide>
<ide> public function every(callable $c)
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function some(callable $c)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function contains($value)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function reduce(callable $c, $zero = null)
<ide> }
<ide> $result = $c($result, $value, $k);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function groupBy($callback)
<ide> foreach ($this as $value) {
<ide> $group[$callback($value)][] = $value;
<ide> }
<add>
<ide> return new Collection($group);
<ide> }
<ide>
<ide> public function indexBy($callback)
<ide> foreach ($this as $value) {
<ide> $group[$callback($value)] = $value;
<ide> }
<add>
<ide> return new Collection($group);
<ide> }
<ide>
<ide> public function countBy($callback)
<ide> $reducer = function ($values, $key, $mr) {
<ide> $mr->emit(count($values), $key);
<ide> };
<add>
<ide> return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
<ide> }
<ide>
<ide> public function shuffle()
<ide> {
<ide> $elements = $this->toArray();
<ide> shuffle($elements);
<add>
<ide> return new Collection($elements);
<ide> }
<ide>
<ide> public function append($items)
<ide> $list = new AppendIterator;
<ide> $list->append($this->unwrap());
<ide> $list->append((new Collection($items))->unwrap());
<add>
<ide> return new Collection($list);
<ide> }
<ide>
<ide> public function combine($keyPath, $valuePath, $groupPath = null)
<ide>
<ide> if (!($options['groupPath'])) {
<ide> $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function nest($idPath, $parentPath)
<ide> $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
<ide> $mapReduce->emit($parents[$id]);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function toArray($preserveKeys = true)
<ide> $iterator = $this->unwrap();
<ide> if ($iterator instanceof ArrayIterator) {
<ide> $items = $iterator->getArrayCopy();
<add>
<ide> return $preserveKeys ? $items : array_values($items);
<ide> }
<ide> // RecursiveIteratorIterator can return duplicate key values causing
<ide> // data loss when converted into an array
<ide> if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
<ide> $preserveKeys = false;
<ide> }
<add>
<ide> return iterator_to_array($this, $preserveKeys);
<ide> }
<ide>
<ide> public function listNested($dir = 'desc', $nestingKey = 'children')
<ide> 'asc' => TreeIterator::CHILD_FIRST,
<ide> 'leaves' => TreeIterator::LEAVES_ONLY
<ide> ];
<add>
<ide> return new TreeIterator(
<ide> new NestIterator($this, $nestingKey),
<ide> isset($modes[$dir]) ? $modes[$dir] : $dir
<ide> public function stopWhen($condition)
<ide> if (!is_callable($condition)) {
<ide> $condition = $this->_createMatcherFilter($condition);
<ide> }
<add>
<ide> return new StoppableIterator($this, $condition);
<ide> }
<ide>
<ide> public function unfold(callable $transformer = null)
<ide> public function through(callable $handler)
<ide> {
<ide> $result = $handler($this);
<add>
<ide> return $result instanceof CollectionInterface ? $result : new Collection($result);
<ide> }
<ide>
<ide> public function zipWith($items, $callable)
<ide> } else {
<ide> $items = [$items];
<ide> }
<add>
<ide> return new ZipIterator(array_merge([$this], $items), $callable);
<ide> }
<ide>
<ide> public function isEmpty()
<ide> foreach ($this->unwrap() as $el) {
<ide> return false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function unwrap()
<ide> while (get_class($iterator) === 'Cake\Collection\Collection') {
<ide> $iterator = $iterator->getInnerIterator();
<ide> }
<add>
<ide> return $iterator;
<ide> }
<ide>
<ide><path>src/Collection/ExtractTrait.php
<ide> protected function _extract($data, $path)
<ide>
<ide> if ($collectionTransform) {
<ide> $rest = implode('.', array_slice($path, $i));
<add>
<ide> return (new Collection($data))->extract($rest);
<ide> }
<ide>
<ide> protected function _extract($data, $path)
<ide> $value = $data[$column];
<ide> $data = $value;
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> protected function _simpleExtract($data, $path)
<ide> $value = $data[$column];
<ide> $data = $value;
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> protected function _createMatcherFilter(array $conditions)
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> };
<ide> }
<ide><path>src/Collection/Iterator/BufferedIterator.php
<ide> public function rewind()
<ide> if ($this->_index === 0 && !$this->_started) {
<ide> $this->_started = true;
<ide> parent::rewind();
<add>
<ide> return;
<ide> }
<ide>
<ide> public function valid()
<ide> $current = $this->_buffer->offsetGet($this->_index);
<ide> $this->_current = $current['value'];
<ide> $this->_key = $current['key'];
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function valid()
<ide> }
<ide>
<ide> $this->_finished = !$valid;
<add>
<ide> return $valid;
<ide> }
<ide>
<ide><path>src/Collection/Iterator/ExtractIterator.php
<ide> public function __construct($items, $path)
<ide> public function current()
<ide> {
<ide> $extractor = $this->_extractor;
<add>
<ide> return $extractor(parent::current());
<ide> }
<ide> }
<ide><path>src/Collection/Iterator/InsertIterator.php
<ide> public function current()
<ide> }
<ide>
<ide> $pointer[$this->_target] = $this->_values->current();
<add>
<ide> return $row;
<ide> }
<ide>
<ide><path>src/Collection/Iterator/MapReduce.php
<ide> public function getIterator()
<ide> if (!$this->_executed) {
<ide> $this->_execute();
<ide> }
<add>
<ide> return new ArrayIterator($this->_result);
<ide> }
<ide>
<ide><path>src/Collection/Iterator/NestIterator.php
<ide> public function __construct($items, $nestKey)
<ide> public function getChildren()
<ide> {
<ide> $property = $this->_propertyExtractor($this->_nestKey);
<add>
<ide> return new self($property($this->current()), $this->_nestKey);
<ide> }
<ide>
<ide><path>src/Collection/Iterator/ReplaceIterator.php
<ide> public function __construct($items, callable $callback)
<ide> public function current()
<ide> {
<ide> $callback = $this->_callback;
<add>
<ide> return $callback(parent::current(), $this->key(), $this->_innerIterator);
<ide> }
<ide> }
<ide><path>src/Collection/Iterator/StoppableIterator.php
<ide> public function valid()
<ide> $current = $this->current();
<ide> $key = $this->key();
<ide> $condition = $this->_condition;
<add>
<ide> return !$condition($current, $key, $this->_innerIterator);
<ide> }
<ide> }
<ide><path>src/Collection/Iterator/TreeIterator.php
<ide> public function printer($valuePath, $keyPath = null, $spacer = '__')
<ide> return $counter++;
<ide> };
<ide> }
<add>
<ide> return new TreePrinter(
<ide> $this->getInnerIterator(),
<ide> $valuePath,
<ide><path>src/Collection/Iterator/TreePrinter.php
<ide> public function __construct($items, $valuePath, $keyPath, $spacer, $mode = Recur
<ide> public function key()
<ide> {
<ide> $extractor = $this->_key;
<add>
<ide> return $extractor($this->_fetchCurrent(), parent::key(), $this);
<ide> }
<ide>
<ide> public function current()
<ide> $extractor = $this->_value;
<ide> $current = $this->_fetchCurrent();
<ide> $spacer = str_repeat($this->_spacer, $this->getDepth());
<add>
<ide> return $spacer . $extractor($current, parent::key(), $this);
<ide> }
<ide>
<ide> protected function _fetchCurrent()
<ide> if ($this->_current !== null) {
<ide> return $this->_current;
<ide> }
<add>
<ide> return $this->_current = parent::current();
<ide> }
<ide> }
<ide><path>src/Console/ConsoleInput.php
<ide> public function read()
<ide> if (strlen($line) > 0) {
<ide> readline_add_history($line);
<ide> }
<add>
<ide> return $line;
<ide> }
<add>
<ide> return fgets($this->_input);
<ide> }
<ide>
<ide> public function dataAvailable($timeout = 0)
<ide> {
<ide> $readFds = [$this->_input];
<ide> $readyFds = stream_select($readFds, $writeFds, $errorFds, $timeout);
<add>
<ide> return ($readyFds > 0);
<ide> }
<ide> }
<ide><path>src/Console/ConsoleInputArgument.php
<ide> public function help($width = 0)
<ide> if (!empty($this->_choices)) {
<ide> $optional .= sprintf(' <comment>(choices: %s)</comment>', implode('|', $this->_choices));
<ide> }
<add>
<ide> return sprintf('%s%s%s', $name, $this->_help, $optional);
<ide> }
<ide>
<ide> public function usage()
<ide> if (!$this->isRequired()) {
<ide> $name = '[' . $name . ']';
<ide> }
<add>
<ide> return $name;
<ide> }
<ide>
<ide> public function validChoice($value)
<ide> )
<ide> );
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function xml(SimpleXmlElement $parent)
<ide> foreach ($this->_choices as $valid) {
<ide> $choices->addChild('choice', $valid);
<ide> }
<add>
<ide> return $parent;
<ide> }
<ide> }
<ide><path>src/Console/ConsoleInputOption.php
<ide> public function help($width = 0)
<ide> if (strlen($name) < $width) {
<ide> $name = str_pad($name, $width, ' ');
<ide> }
<add>
<ide> return sprintf('%s%s%s', $name, $this->_help, $default);
<ide> }
<ide>
<ide> public function usage()
<ide> if (!empty($this->_choices)) {
<ide> $default = ' ' . implode('|', $this->_choices);
<ide> }
<add>
<ide> return sprintf('[%s%s]', $name, $default);
<ide> }
<ide>
<ide> public function validChoice($value)
<ide> )
<ide> );
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function xml(SimpleXmlElement $parent)
<ide> foreach ($this->_choices as $valid) {
<ide> $choices->addChild('choice', $valid);
<ide> }
<add>
<ide> return $parent;
<ide> }
<ide> }
<ide><path>src/Console/ConsoleInputSubcommand.php
<ide> public function help($width = 0)
<ide> if (strlen($name) < $width) {
<ide> $name = str_pad($name, $width, ' ');
<ide> }
<add>
<ide> return $name . $this->_help;
<ide> }
<ide>
<ide> public function parser()
<ide> if ($this->_parser instanceof ConsoleOptionParser) {
<ide> return $this->_parser;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function xml(SimpleXmlElement $parent)
<ide> $command = $parent->addChild('command');
<ide> $command->addAttribute('name', $this->_name);
<ide> $command->addAttribute('help', $this->_help);
<add>
<ide> return $parent;
<ide> }
<ide> }
<ide><path>src/Console/ConsoleIo.php
<ide> public function level($level = null)
<ide> if ($level !== null) {
<ide> $this->_level = $level;
<ide> }
<add>
<ide> return $this->_level;
<ide> }
<ide>
<ide> public function out($message = '', $newlines = 1, $level = ConsoleIo::NORMAL)
<ide> {
<ide> if ($level <= $this->_level) {
<ide> $this->_lastWritten = $this->_out->write($message, $newlines);
<add>
<ide> return $this->_lastWritten;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function askChoice($prompt, $options, $default = null)
<ide> while ($in === '' || !in_array($in, $options)) {
<ide> $in = $this->_getInput($prompt, $printOptions, $default);
<ide> }
<add>
<ide> return $in;
<ide> }
<ide>
<ide> protected function _getInput($prompt, $options, $default)
<ide> if ($default !== null && ($result === '' || $result === null)) {
<ide> return $default;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function setLoggers($enable)
<ide> public function helper($name, array $settings = [])
<ide> {
<ide> $name = ucfirst($name);
<add>
<ide> return $this->_helpers->load($name, $settings);
<ide> }
<ide> }
<ide><path>src/Console/ConsoleOptionParser.php
<ide> public static function buildFromArray($spec, $defaultOptions = true)
<ide> if (!empty($spec['epilog'])) {
<ide> $parser->epilog($spec['epilog']);
<ide> }
<add>
<ide> return $parser;
<ide> }
<ide>
<ide> public function toArray()
<ide> 'description' => $this->_description,
<ide> 'epilog' => $this->_epilog
<ide> ];
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function merge($spec)
<ide> if (!empty($spec['epilog'])) {
<ide> $this->epilog($spec['epilog']);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function command($text = null)
<ide> {
<ide> if ($text !== null) {
<ide> $this->_command = Inflector::underscore($text);
<add>
<ide> return $this;
<ide> }
<add>
<ide> return $this->_command;
<ide> }
<ide>
<ide> public function description($text = null)
<ide> $text = implode("\n", $text);
<ide> }
<ide> $this->_description = $text;
<add>
<ide> return $this;
<ide> }
<add>
<ide> return $this->_description;
<ide> }
<ide>
<ide> public function epilog($text = null)
<ide> $text = implode("\n", $text);
<ide> }
<ide> $this->_epilog = $text;
<add>
<ide> return $this;
<ide> }
<add>
<ide> return $this->_epilog;
<ide> }
<ide>
<ide> public function addOption($name, array $options = [])
<ide> $this->_shortOptions[$option->short()] = $name;
<ide> asort($this->_shortOptions);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addOption($name, array $options = [])
<ide> public function removeOption($name)
<ide> {
<ide> unset($this->_options[$name]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addArgument($name, array $params = [])
<ide> }
<ide> $this->_args[$index] = $arg;
<ide> ksort($this->_args);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addArguments(array $args)
<ide> }
<ide> $this->addArgument($name, $params);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addOptions(array $options)
<ide> }
<ide> $this->addOption($name, $params);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addSubcommand($name, array $options = [])
<ide> }
<ide> $this->_subcommands[$name] = $command;
<ide> asort($this->_subcommands);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addSubcommand($name, array $options = [])
<ide> public function removeSubcommand($name)
<ide> {
<ide> unset($this->_subcommands[$name]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addSubcommands(array $commands)
<ide> }
<ide> $this->addSubcommand($name, $params);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function parse($argv)
<ide> $params[$name] = false;
<ide> }
<ide> }
<add>
<ide> return [$params, $args];
<ide> }
<ide>
<ide> public function help($subcommand = null, $format = 'text', $width = 72)
<ide> ) {
<ide> $subparser = $this->_subcommands[$subcommand]->parser();
<ide> $subparser->command($this->command() . ' ' . $subparser->command());
<add>
<ide> return $subparser->help(null, $format, $width);
<ide> }
<ide>
<ide> protected function _parseLongOption($option, $params)
<ide> list($name, $value) = explode('=', $name, 2);
<ide> array_unshift($this->_tokens, $value);
<ide> }
<add>
<ide> return $this->_parseOption($name, $params);
<ide> }
<ide>
<ide> protected function _parseShortOption($option, $params)
<ide> throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
<ide> }
<ide> $name = $this->_shortOptions[$key];
<add>
<ide> return $this->_parseOption($name, $params);
<ide> }
<ide>
<ide> protected function _parseOption($name, $params)
<ide> }
<ide> if ($option->validChoice($value)) {
<ide> $params[$name] = $value;
<add>
<ide> return $params;
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> protected function _optionExists($name)
<ide> if ($name{0} === '-' && $name{1} !== '-') {
<ide> return isset($this->_shortOptions[$name{1}]);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _parseArg($argument, $args)
<ide> {
<ide> if (empty($this->_args)) {
<ide> $args[] = $argument;
<add>
<ide> return $args;
<ide> }
<ide> $next = count($args);
<ide> protected function _parseArg($argument, $args)
<ide>
<ide> if ($this->_args[$next]->validChoice($argument)) {
<ide> $args[] = $argument;
<add>
<ide> return $args;
<ide> }
<ide> }
<ide><path>src/Console/ConsoleOutput.php
<ide> public function write($message, $newlines = 1)
<ide> if (is_array($message)) {
<ide> $message = implode(static::LF, $message);
<ide> }
<add>
<ide> return $this->_write($this->styleText($message . str_repeat(static::LF, $newlines)));
<ide> }
<ide>
<ide> public function styleText($text)
<ide> }
<ide> if ($this->_outputAs == static::PLAIN) {
<ide> $tags = implode('|', array_keys(static::$_styles));
<add>
<ide> return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
<ide> }
<add>
<ide> return preg_replace_callback(
<ide> '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims',
<ide> [$this, '_replaceTags'],
<ide> protected function _replaceTags($matches)
<ide> $styleInfo[] = static::$_options[$option];
<ide> }
<ide> }
<add>
<ide> return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
<ide> }
<ide>
<ide> public function styles($style = null, $definition = null)
<ide> }
<ide> if ($definition === false) {
<ide> unset(static::$_styles[$style]);
<add>
<ide> return true;
<ide> }
<ide> static::$_styles[$style] = $definition;
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>src/Console/HelpFormatter.php
<ide> public function text($width = 72)
<ide> $out[] = Text::wrap($epilog, $width);
<ide> $out[] = '';
<ide> }
<add>
<ide> return implode("\n", $out);
<ide> }
<ide>
<ide> protected function _generateUsage()
<ide> $args = ['[arguments]'];
<ide> }
<ide> $usage = array_merge($usage, $args);
<add>
<ide> return implode(' ', $usage);
<ide> }
<ide>
<ide> protected function _getMaxLength($collection)
<ide> foreach ($collection as $item) {
<ide> $max = (strlen($item->name()) > $max) ? strlen($item->name()) : $max;
<ide> }
<add>
<ide> return $max;
<ide> }
<ide>
<ide> public function xml($string = true)
<ide> foreach ($parser->arguments() as $argument) {
<ide> $argument->xml($arguments);
<ide> }
<add>
<ide> return $string ? $xml->asXml() : $xml;
<ide> }
<ide> }
<ide><path>src/Console/Shell.php
<ide> public function io(ConsoleIo $io = null)
<ide> if ($io !== null) {
<ide> $this->_io = $io;
<ide> }
<add>
<ide> return $this->_io;
<ide> }
<ide>
<ide> public function loadTasks()
<ide> }
<ide> $this->_taskMap = $this->Tasks->normalizeArray((array)$this->tasks);
<ide> $this->taskNames = array_merge($this->taskNames, array_keys($this->_taskMap));
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function hasMethod($name)
<ide> if (!$method->isPublic()) {
<ide> return false;
<ide> }
<add>
<ide> return $method->getDeclaringClass()->name !== 'Cake\Console\Shell';
<ide> } catch (ReflectionException $e) {
<ide> return false;
<ide> public function dispatchShell()
<ide> }
<ide>
<ide> $dispatcher = new ShellDispatcher($args, false);
<add>
<ide> return $dispatcher->dispatch($extra);
<ide> }
<ide>
<ide> public function parseDispatchArguments($args)
<ide>
<ide> if (is_string($args[0]) && count($args) === 1) {
<ide> $args = explode(' ', $args[0]);
<add>
<ide> return [$args, $extra];
<ide> }
<ide>
<ide> public function runCommand($argv, $autoMethod = false, $extra = [])
<ide> } catch (ConsoleException $e) {
<ide> $this->err('<error>Error: ' . $e->getMessage() . '</error>');
<ide> $this->out($this->OptionParser->help($command));
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function runCommand($argv, $autoMethod = false, $extra = [])
<ide> if ($isMethod && $autoMethod && count($subcommands) === 0) {
<ide> array_shift($this->args);
<ide> $this->startup();
<add>
<ide> return call_user_func_array([$this, $method], $this->args);
<ide> }
<ide>
<ide> if ($isMethod && isset($subcommands[$command])) {
<ide> $this->startup();
<add>
<ide> return call_user_func_array([$this, $method], $this->args);
<ide> }
<ide>
<ide> if ($this->hasTask($command) && isset($subcommands[$command])) {
<ide> $this->startup();
<ide> array_shift($argv);
<add>
<ide> return $this->{$method}->runCommand($argv, false);
<ide> }
<ide>
<ide> if ($this->hasMethod('main')) {
<ide> $this->command = 'main';
<ide> $this->startup();
<add>
<ide> return call_user_func_array([$this, 'main'], $this->args);
<ide> }
<ide>
<ide> $this->out($this->OptionParser->help($command));
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _displayHelp($command)
<ide> } else {
<ide> $this->_welcome();
<ide> }
<add>
<ide> return $this->out($this->OptionParser->help($command, $format));
<ide> }
<ide>
<ide> public function getOptionParser()
<ide> {
<ide> $name = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
<ide> $parser = new ConsoleOptionParser($name);
<add>
<ide> return $parser;
<ide> }
<ide>
<ide> public function __get($name)
<ide> $this->{$name}->initialize();
<ide> $this->{$name}->loadTasks();
<ide> }
<add>
<ide> return $this->{$name};
<ide> }
<ide>
<ide> public function param($name)
<ide> if (!isset($this->params[$name])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->params[$name];
<ide> }
<ide>
<ide> public function in($prompt, $options = null, $default = null)
<ide> if ($options) {
<ide> return $this->_io->askChoice($prompt, $options, $default);
<ide> }
<add>
<ide> return $this->_io->ask($prompt, $default);
<ide> }
<ide>
<ide> public function error($title, $message = null, $exitCode = self::CODE_ERROR)
<ide> }
<ide>
<ide> $this->_stop($exitCode);
<add>
<ide> return $exitCode;
<ide> }
<ide>
<ide> public function createFile($path, $contents)
<ide> if (strtolower($key) === 'q') {
<ide> $this->_io->out('<error>Quitting</error>.', 2);
<ide> $this->_stop();
<add>
<ide> return false;
<ide> }
<ide> if (strtolower($key) === 'a') {
<ide> public function createFile($path, $contents)
<ide> }
<ide> if (strtolower($key) !== 'y') {
<ide> $this->_io->out(sprintf('Skip `%s`', $path), 2);
<add>
<ide> return false;
<ide> }
<ide> } else {
<ide> public function createFile($path, $contents)
<ide> if ($File->exists() && $File->writable()) {
<ide> $File->write($contents);
<ide> $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path));
<add>
<ide> return true;
<ide> }
<ide>
<ide> $this->_io->err(sprintf('<error>Could not write to `%s`</error>.', $path), 2);
<add>
<ide> return false;
<ide> } finally {
<ide> $File->close();
<ide> public function shortPath($file)
<ide> $shortPath = str_replace(ROOT, null, $file);
<ide> $shortPath = str_replace('..' . DIRECTORY_SEPARATOR, '', $shortPath);
<ide> $shortPath = str_replace(DIRECTORY_SEPARATOR, '/', $shortPath);
<add>
<ide> return str_replace('//', DIRECTORY_SEPARATOR, $shortPath);
<ide> }
<ide>
<ide><path>src/Console/ShellDispatcher.php
<ide> public static function resetAliases()
<ide> public static function run($argv, $extra = [])
<ide> {
<ide> $dispatcher = new ShellDispatcher($argv);
<add>
<ide> return $dispatcher->dispatch($extra);
<ide> }
<ide>
<ide> public function dispatch($extra = [])
<ide> if ($result === null || $result === true) {
<ide> return 0;
<ide> }
<add>
<ide> return 1;
<ide> }
<ide>
<ide> protected function _dispatch($extra = [])
<ide>
<ide> if (!$shell) {
<ide> $this->help();
<add>
<ide> return false;
<ide> }
<ide> if (in_array($shell, ['help', '--help', '-h'])) {
<ide> $this->help();
<add>
<ide> return true;
<ide> }
<ide> if (in_array($shell, ['version', '--version'])) {
<ide> $this->version();
<add>
<ide> return true;
<ide> }
<ide>
<ide> $Shell = $this->findShell($shell);
<ide>
<ide> $Shell->initialize();
<add>
<ide> return $Shell->runCommand($this->args, true, $extra);
<ide> }
<ide>
<ide> protected function _handleAlias($shell)
<ide> }
<ide>
<ide> $class = array_map('Cake\Utility\Inflector::camelize', explode('.', $shell));
<add>
<ide> return implode('.', $class);
<ide> }
<ide>
<ide> protected function _shellExists($shell)
<ide> if (class_exists($class)) {
<ide> return $class;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _createShell($className, $shortName)
<ide> list($plugin) = pluginSplit($shortName);
<ide> $instance = new $className();
<ide> $instance->plugin = trim($plugin, '.');
<add>
<ide> return $instance;
<ide> }
<ide>
<ide><path>src/Controller/Component.php
<ide> public function implementedEvents()
<ide> $events[$event] = $method;
<ide> }
<ide> }
<add>
<ide> return $events;
<ide> }
<ide>
<ide><path>src/Controller/Component/AuthComponent.php
<ide> public function authCheck(Event $event)
<ide> if ($result instanceof Response) {
<ide> $event->stopPropagation();
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function authCheck(Event $event)
<ide> }
<ide>
<ide> $event->stopPropagation();
<add>
<ide> return $this->_unauthorized($controller);
<ide> }
<ide>
<ide> public function implementedEvents()
<ide> protected function _isAllowed(Controller $controller)
<ide> {
<ide> $action = strtolower($controller->request->params['action']);
<add>
<ide> return in_array($action, array_map('strtolower', $this->allowedActions));
<ide> }
<ide>
<ide> protected function _unauthenticated(Controller $controller)
<ide> if (!$controller->request->is('ajax')) {
<ide> $this->flash($this->_config['authError']);
<ide> $this->storage()->redirectUrl($controller->request->here(false));
<add>
<ide> return $controller->redirect($this->_config['loginAction']);
<ide> }
<ide>
<ide> protected function _unauthenticated(Controller $controller)
<ide> $this->RequestHandler->ajaxLayout
<ide> );
<ide> $response->statusCode(403);
<add>
<ide> return $response;
<ide> }
<ide> $this->response->statusCode(403);
<add>
<ide> return $this->response;
<ide> }
<ide>
<ide> protected function _unauthorized(Controller $controller)
<ide> } else {
<ide> $url = $this->_config['unauthorizedRedirect'];
<ide> }
<add>
<ide> return $controller->redirect($url);
<ide> }
<ide>
<ide> public function isAuthorized($user = null, Request $request = null)
<ide> foreach ($this->_authorizeObjects as $authorizer) {
<ide> if ($authorizer->authorize($user, $request) === true) {
<ide> $this->_authorizationProvider = $authorizer;
<add>
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function constructAuthorize()
<ide> $config = (array)$config + $global;
<ide> $this->_authorizeObjects[$alias] = new $className($this->_registry, $config);
<ide> }
<add>
<ide> return $this->_authorizeObjects;
<ide> }
<ide>
<ide> public function allow($actions = null)
<ide> if ($actions === null) {
<ide> $controller = $this->_registry->getController();
<ide> $this->allowedActions = get_class_methods($controller);
<add>
<ide> return;
<ide> }
<ide> $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
<ide> public function deny($actions = null)
<ide> {
<ide> if ($actions === null) {
<ide> $this->allowedActions = [];
<add>
<ide> return;
<ide> }
<ide> foreach ((array)$actions as $action) {
<ide> public function logout()
<ide> $this->dispatchEvent('Auth.logout', [$user]);
<ide> $this->storage()->redirectUrl(false);
<ide> $this->storage()->delete();
<add>
<ide> return Router::normalize($this->_config['logoutRedirect']);
<ide> }
<ide>
<ide> public function user($key = null)
<ide> if ($key === null) {
<ide> return $user;
<ide> }
<add>
<ide> return Hash::get($user, $key);
<ide> }
<ide>
<ide> protected function _getUser()
<ide> $user = $this->user();
<ide> if ($user) {
<ide> $this->storage()->redirectUrl(false);
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _getUser()
<ide> $result = $event->result;
<ide> }
<ide> $this->storage()->write($result);
<add>
<ide> return true;
<ide> }
<ide> }
<ide> public function redirectUrl($url = null)
<ide> if (is_array($redir)) {
<ide> return Router::url($redir + ['_base' => false]);
<ide> }
<add>
<ide> return $redir;
<ide> }
<ide>
<ide> public function identify()
<ide> if ($event->result !== null) {
<ide> return $event->result;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function constructAuthenticate()
<ide> $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
<ide> $this->eventManager()->on($this->_authenticateObjects[$alias]);
<ide> }
<add>
<ide> return $this->_authenticateObjects;
<ide> }
<ide>
<ide> public function storage(StorageInterface $storage = null)
<ide> {
<ide> if ($storage !== null) {
<ide> $this->_storage = $storage;
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function __set($name, $value)
<ide>
<ide> if ($value === false) {
<ide> $this->config('storage', 'Memory');
<add>
<ide> return;
<ide> }
<ide>
<ide> $this->config('storage', 'Session');
<ide> $this->storage()->config('key', $value);
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/Controller/Component/CookieComponent.php
<ide> public function configKey($keyname, $option = null, $value = null)
<ide> if ($option === null) {
<ide> $default = $this->_config;
<ide> $local = isset($this->_keyConfig[$keyname]) ? $this->_keyConfig[$keyname] : [];
<add>
<ide> return $local + $default;
<ide> }
<ide> if (!is_array($option)) {
<ide> $option = [$option => $value];
<ide> }
<ide> $this->_keyConfig[$keyname] = $option;
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function write($key, $value = null)
<ide> public function read($key = null)
<ide> {
<ide> $this->_load($key);
<add>
<ide> return Hash::get($this->_values, $key);
<ide> }
<ide>
<ide> public function check($key = null)
<ide> if (empty($key)) {
<ide> return false;
<ide> }
<add>
<ide> return $this->read($key) !== null;
<ide> }
<ide>
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> public function mergeOptions($alias, $settings)
<ide> $defaults = $this->getDefaults($alias, $settings);
<ide> $request = $this->_registry->getController()->request;
<ide> $request = array_intersect_key($request->query, array_flip($this->_config['whitelist']));
<add>
<ide> return array_merge($defaults, $request);
<ide> }
<ide>
<ide> public function getDefaults($alias, $defaults)
<ide> ) {
<ide> $defaults['maxLimit'] = $defaults['limit'];
<ide> }
<add>
<ide> return $defaults + $this->config();
<ide> }
<ide>
<ide> public function validateSort(RepositoryInterface $object, array $options)
<ide> $inWhitelist = in_array($field, $options['sortWhitelist'], true);
<ide> if (!$inWhitelist) {
<ide> $options['order'] = [];
<add>
<ide> return $options;
<ide> }
<ide> }
<ide>
<ide> $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist);
<add>
<ide> return $options;
<ide> }
<ide>
<ide> protected function _prefix(RepositoryInterface $object, $order, $whitelisted = f
<ide> $tableOrder[$alias . '.' . $field] = $value;
<ide> }
<ide> }
<add>
<ide> return $tableOrder;
<ide> }
<ide>
<ide> public function checkLimit(array $options)
<ide> $options['limit'] = 1;
<ide> }
<ide> $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1);
<add>
<ide> return $options;
<ide> }
<ide> }
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function convertXml($xml)
<ide> if (isset($xml->data)) {
<ide> return Xml::toArray($xml->data);
<ide> }
<add>
<ide> return Xml::toArray($xml);
<ide> } catch (XmlException $e) {
<ide> return [];
<ide> public function beforeRedirect(Event $event, $url, Response $response)
<ide> 'cookies' => $request->cookies
<ide> ]));
<ide> $response->statusCode(200);
<add>
<ide> return $response;
<ide> }
<ide>
<ide> public function isAtom()
<ide> public function isMobile()
<ide> {
<ide> $request = $this->request;
<add>
<ide> return $request->is('mobile') || $this->accepts('wap');
<ide> }
<ide>
<ide> public function accepts($type = null)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide> if (is_string($type)) {
<ide> return in_array($this->mapAlias($type), $accepted);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function requestedWith($type = null)
<ide> return $t;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function prefers($type = null)
<ide> if (empty($this->ext) && !empty($accepts)) {
<ide> return $accepts[0];
<ide> }
<add>
<ide> return $this->ext;
<ide> }
<ide>
<ide> public function prefers($type = null)
<ide> if (!empty($this->ext)) {
<ide> return in_array($this->ext, $types);
<ide> }
<add>
<ide> return in_array($types[0], $accepts);
<ide> }
<ide>
<ide> $intersect = array_values(array_intersect($accepts, $types));
<ide> if (empty($intersect)) {
<ide> return false;
<ide> }
<add>
<ide> return $intersect[0];
<ide> }
<ide>
<ide> public function respondAs($type, array $options = [])
<ide> if (!empty($options['attachment'])) {
<ide> $response->download($options['attachment']);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function respondAs($type, array $options = [])
<ide> public function responseType()
<ide> {
<ide> $response = $this->response;
<add>
<ide> return $response->mapType($response->type());
<ide> }
<ide>
<ide> public function mapAlias($alias)
<ide> if (is_array($type)) {
<ide> return $type[0];
<ide> }
<add>
<ide> return $type;
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function viewClassMap($type = null, $viewClass = null)
<ide> } elseif (is_array($type)) {
<ide> $this->config('viewClassMap', $type, true);
<ide> }
<add>
<ide> return $this->config('viewClassMap');
<ide> }
<ide> }
<ide><path>src/Controller/Component/SecurityComponent.php
<ide> public function blackHole(Controller $controller, $error = '', SecurityException
<ide> if (!$this->_config['blackHoleCallback']) {
<ide> $this->_throwException($exception);
<ide> }
<add>
<ide> return $this->_callback($controller, $this->_config['blackHoleCallback'], [$error, $exception]);
<ide> }
<ide>
<ide> protected function _secureRequired(Controller $controller)
<ide> }
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _authRequired(Controller $controller)
<ide> }
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _validToken(Controller $controller)
<ide> if (strpos($token, ':')) {
<ide> list($token, ) = explode(':', $token, 2);
<ide> }
<add>
<ide> return $token;
<ide> }
<ide>
<ide> protected function _fieldsList(array $check)
<ide> sort($fieldList, SORT_STRING);
<ide> ksort($lockedFields, SORT_STRING);
<ide> $fieldList += $lockedFields;
<add>
<ide> return $fieldList;
<ide> }
<ide>
<ide> protected function _sortedUnlocked($data)
<ide> $unlocked = $this->_unlocked($data);
<ide> $unlocked = explode('|', $unlocked);
<ide> sort($unlocked, SORT_STRING);
<add>
<ide> return implode('|', $unlocked);
<ide> }
<ide>
<ide> protected function _debugPostTokenNotMatching(Controller $controller, $hashParts
<ide> );
<ide>
<ide> $messages = array_merge($messages, $fieldsMessages, $unlockFieldsMessages);
<add>
<ide> return implode(', ', $messages);
<ide> }
<ide>
<ide> protected function _debugCheckFields($dataFields, $expectedFields = [], $intKeyM
<ide> if ($expectedFieldsMessage !== null) {
<ide> $messages[] = $expectedFieldsMessage;
<ide> }
<add>
<ide> return $messages;
<ide> }
<ide>
<ide> public function generateToken(Request $request)
<ide> if ($this->session->check('_Token')) {
<ide> $request->params['_Token'] = $this->session->read('_Token');
<ide> }
<add>
<ide> return false;
<ide> }
<ide> $token = [
<ide> public function generateToken(Request $request)
<ide> $request->params['_Token'] = [
<ide> 'unlockedFields' => $token['unlockedFields']
<ide> ];
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _callback(Controller $controller, $method, $params = [])
<ide> if (!is_callable([$controller, $method])) {
<ide> throw new BadRequestException('The request has been black-holed');
<ide> }
<add>
<ide> return call_user_func_array([&$controller, $method], empty($params) ? null : $params);
<ide> }
<ide>
<ide> protected function _debugExpectedFields($expectedFields = [], $missingMessage =
<ide> $expectedFieldNames[] = $key;
<ide> }
<ide> }
<add>
<ide> return sprintf($missingMessage, implode(', ', $expectedFieldNames));
<ide> }
<ide> }
<ide><path>src/Controller/ComponentRegistry.php
<ide> protected function _create($class, $alias, $config)
<ide> if ($enable) {
<ide> $this->eventManager()->on($instance);
<ide> }
<add>
<ide> return $instance;
<ide> }
<ide> }
<ide><path>src/Controller/Controller.php
<ide> public function components($components = null)
<ide> $components->setController($this);
<ide> $this->_components = $components;
<ide> }
<add>
<ide> return $this->_components;
<ide> }
<ide>
<ide> public function loadComponent($name, array $config = [])
<ide> {
<ide> list(, $prop) = pluginSplit($name);
<ide> $this->{$prop} = $this->components()->load($name, $config);
<add>
<ide> return $this->{$prop};
<ide> }
<ide>
<ide> public function __get($name)
<ide> sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $name, $method),
<ide> E_USER_DEPRECATED
<ide> );
<add>
<ide> return $this->viewBuilder()->{$name}();
<ide> }
<ide>
<ide> list($plugin, $class) = pluginSplit($this->modelClass, true);
<ide> if ($class !== $name) {
<ide> return false;
<ide> }
<add>
<ide> return $this->loadModel($plugin . $class);
<ide> }
<ide>
<ide> public function __set($name, $value)
<ide> E_USER_DEPRECATED
<ide> );
<ide> $this->viewBuilder()->{$method}($value);
<add>
<ide> return;
<ide> }
<ide>
<ide> public function invokeAction()
<ide> ]);
<ide> }
<ide> $callable = [$this, $request->params['action']];
<add>
<ide> return call_user_func_array($callable, $request->params['pass']);
<ide> }
<ide>
<ide> public function setAction($action)
<ide> $this->request->params['action'] = $action;
<ide> $args = func_get_args();
<ide> unset($args[0]);
<add>
<ide> return call_user_func_array([&$this, $action], $args);
<ide> }
<ide>
<ide> public function render($view = null, $layout = null)
<ide>
<ide> $this->View = $this->createView();
<ide> $this->response->body($this->View->render($view, $layout));
<add>
<ide> return $this->response;
<ide> }
<ide>
<ide> protected function _viewPath()
<ide> );
<ide> $viewPath = implode(DIRECTORY_SEPARATOR, $prefixes) . DIRECTORY_SEPARATOR . $viewPath;
<ide> }
<add>
<ide> return $viewPath;
<ide> }
<ide>
<ide> public function referer($default = null, $local = false)
<ide> if ($referer === '/' && $default && $default !== $referer) {
<ide> return Router::url($default, !$local);
<ide> }
<add>
<ide> return $referer;
<ide> }
<ide>
<ide> public function paginate($object = null)
<ide> if (empty($table)) {
<ide> throw new RuntimeException('Unable to locate an object compatible with paginate.');
<ide> }
<add>
<ide> return $this->Paginator->paginate($table, $this->paginate);
<ide> }
<ide>
<ide><path>src/Core/App.php
<ide> public static function className($class, $type = '', $suffix = '')
<ide> if (static::_classExistsInBase($fullname, 'Cake')) {
<ide> return 'Cake' . $fullname;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function path($type, $plugin = null)
<ide> if (!empty($plugin)) {
<ide> return [Plugin::classPath($plugin) . $type . DIRECTORY_SEPARATOR];
<ide> }
<add>
<ide> return [APP . $type . DIRECTORY_SEPARATOR];
<ide> }
<ide>
<ide><path>src/Core/ClassLoader.php
<ide> protected function _requireFile($file)
<ide> {
<ide> if (file_exists($file)) {
<ide> require $file;
<add>
<ide> return true;
<ide> }
<add>
<ide> return false;
<ide> }
<ide> }
<ide><path>src/Core/Configure.php
<ide> public static function write($config, $value = null)
<ide> ini_set('display_errors', $config['debug'] ? 1 : 0);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function read($var = null)
<ide> if ($var === null) {
<ide> return static::$_values;
<ide> }
<add>
<ide> return Hash::get(static::$_values, $var);
<ide> }
<ide>
<ide> public static function check($var)
<ide> if (empty($var)) {
<ide> return false;
<ide> }
<add>
<ide> return static::read($var) !== null;
<ide> }
<ide>
<ide> public static function readOrFail($var)
<ide> if (static::check($var) === false) {
<ide> throw new RuntimeException(sprintf('Expected configuration key "%s" not found.', $var));
<ide> }
<add>
<ide> return static::read($var);
<ide> }
<ide>
<ide> public static function consume($var)
<ide> }
<ide> $value = static::$_values[$var];
<ide> unset(static::$_values[$var]);
<add>
<ide> return $value;
<ide> }
<ide> $value = Hash::get(static::$_values, $var);
<ide> static::delete($var);
<add>
<ide> return $value;
<ide> }
<ide>
<ide> public static function configured($name = null)
<ide> if ($name !== null) {
<ide> return isset(static::$_engines[$name]);
<ide> }
<add>
<ide> return array_keys(static::$_engines);
<ide> }
<ide>
<ide> public static function drop($name)
<ide> return false;
<ide> }
<ide> unset(static::$_engines[$name]);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function dump($key, $config = 'default', $keys = [])
<ide> if (!empty($keys) && is_array($keys)) {
<ide> $values = array_intersect_key($values, array_flip($keys));
<ide> }
<add>
<ide> return (bool)$engine->dump($key, $values);
<ide> }
<ide>
<ide> protected static function _getEngine($config)
<ide> }
<ide> static::config($config, new PhpConfig());
<ide> }
<add>
<ide> return static::$_engines[$config];
<ide> }
<ide>
<ide> public static function version()
<ide> $config = require CORE_PATH . 'config/config.php';
<ide> static::write($config);
<ide> }
<add>
<ide> return static::$_values['Cake']['version'];
<ide> }
<ide>
<ide> public static function store($name, $cacheConfig = 'default', $data = null)
<ide> if ($data === null) {
<ide> $data = static::$_values;
<ide> }
<add>
<ide> return Cache::write($name, $data, $cacheConfig);
<ide> }
<ide>
<ide> public static function restore($name, $cacheConfig = 'default')
<ide> if ($values) {
<ide> return static::write($values);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function restore($name, $cacheConfig = 'default')
<ide> public static function clear()
<ide> {
<ide> static::$_values = [];
<add>
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Core/Configure/Engine/IniConfig.php
<ide> public function read($key)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $values;
<ide> }
<ide>
<ide> protected function _parseNestedValues($values)
<ide> $values[$key] = $value;
<ide> }
<ide> }
<add>
<ide> return $values;
<ide> }
<ide>
<ide> public function dump($key, array $data)
<ide> $contents = trim(implode("\n", $result));
<ide>
<ide> $filename = $this->_getFilePath($key);
<add>
<ide> return file_put_contents($filename, $contents) > 0;
<ide> }
<ide>
<ide> protected function _value($value)
<ide> if ($value === false) {
<ide> return 'false';
<ide> }
<add>
<ide> return (string)$value;
<ide> }
<ide> }
<ide><path>src/Core/Configure/Engine/JsonConfig.php
<ide> public function read($key)
<ide> $key
<ide> ));
<ide> }
<add>
<ide> return $values;
<ide> }
<ide>
<ide> public function read($key)
<ide> public function dump($key, array $data)
<ide> {
<ide> $filename = $this->_getFilePath($key);
<add>
<ide> return file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT)) > 0;
<ide> }
<ide> }
<ide><path>src/Core/Configure/Engine/PhpConfig.php
<ide> public function dump($key, array $data)
<ide> $contents = '<?php' . "\n" . 'return ' . var_export($data, true) . ';';
<ide>
<ide> $filename = $this->_getFilePath($key);
<add>
<ide> return file_put_contents($filename, $contents) > 0;
<ide> }
<ide> }
<ide><path>src/Core/ConventionsTrait.php
<ide> protected function _entityName($name)
<ide> protected function _modelKey($name)
<ide> {
<ide> list(, $name) = pluginSplit($name);
<add>
<ide> return Inflector::underscore(Inflector::singularize($name)) . '_id';
<ide> }
<ide>
<ide> protected function _modelKey($name)
<ide> protected function _modelNameFromKey($key)
<ide> {
<ide> $key = str_replace('_id', '', $key);
<add>
<ide> return Inflector::camelize(Inflector::pluralize($key));
<ide> }
<ide>
<ide> protected function _pluginPath($pluginName)
<ide> if (Plugin::loaded($pluginName)) {
<ide> return Plugin::path($pluginName);
<ide> }
<add>
<ide> return current(App::path('Plugin')) . $pluginName . DIRECTORY_SEPARATOR;
<ide> }
<ide>
<ide><path>src/Core/InstanceConfigTrait.php
<ide> public function config($key = null, $value = null, $merge = true)
<ide>
<ide> if (is_array($key) || func_num_args() >= 2) {
<ide> $this->_configWrite($key, $value, $merge);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function configShallow($key, $value = null)
<ide> }
<ide>
<ide> $this->_configWrite($key, $value, 'shallow');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _configWrite($key, $value, $merge = false)
<ide> {
<ide> if (is_string($key) && $value === null) {
<ide> $this->_configDelete($key);
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _configWrite($key, $value, $merge = false)
<ide> } else {
<ide> $this->_config = Hash::merge($this->_config, Hash::expand($update));
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> if (is_array($key)) {
<ide> foreach ($key as $k => $val) {
<ide> $this->_configWrite($k, $val);
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> if (strpos($key, '.') === false) {
<ide> $this->_config[$key] = $value;
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _configDelete($key)
<ide> {
<ide> if (strpos($key, '.') === false) {
<ide> unset($this->_config[$key]);
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/Core/ObjectRegistry.php
<ide> public function load($objectName, $config = [])
<ide> }
<ide> $instance = $this->_create($className, $name, $config);
<ide> $this->_loaded[$name] = $instance;
<add>
<ide> return $instance;
<ide> }
<ide>
<ide> public function get($name)
<ide> if (isset($this->_loaded[$name])) {
<ide> return $this->_loaded[$name];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function normalizeArray($objects)
<ide> list(, $name) = pluginSplit($objectName);
<ide> $normal[$name] = ['class' => $objectName, 'config' => $config];
<ide> }
<add>
<ide> return $normal;
<ide> }
<ide>
<ide> public function __debugInfo()
<ide> if (isset($properties['_loaded'])) {
<ide> $properties['_loaded'] = array_keys($properties['_loaded']);
<ide> }
<add>
<ide> return $properties;
<ide> }
<ide> }
<ide><path>src/Core/Plugin.php
<ide> public static function load($plugin, array $config = [])
<ide> list($name, $conf) = (is_numeric($name)) ? [$conf, $config] : [$name, $conf];
<ide> static::load($name, $conf);
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> protected static function _loadConfig()
<ide> $vendorFile = dirname(dirname(dirname(dirname(__DIR__)))) . DIRECTORY_SEPARATOR . 'cakephp-plugins.php';
<ide> if (!file_exists($vendorFile)) {
<ide> Configure::write(['plugins' => []]);
<add>
<ide> return;
<ide> }
<ide> }
<ide> public static function path($plugin)
<ide> if (empty(static::$_plugins[$plugin])) {
<ide> throw new MissingPluginException(['plugin' => $plugin]);
<ide> }
<add>
<ide> return static::$_plugins[$plugin]['path'];
<ide> }
<ide>
<ide> public static function classPath($plugin)
<ide> if (empty(static::$_plugins[$plugin])) {
<ide> throw new MissingPluginException(['plugin' => $plugin]);
<ide> }
<add>
<ide> return static::$_plugins[$plugin]['classPath'];
<ide> }
<ide>
<ide> public static function configPath($plugin)
<ide> if (empty(static::$_plugins[$plugin])) {
<ide> throw new MissingPluginException(['plugin' => $plugin]);
<ide> }
<add>
<ide> return static::$_plugins[$plugin]['configPath'];
<ide> }
<ide>
<ide> public static function routes($plugin = null)
<ide> foreach (static::loaded() as $p) {
<ide> static::routes($p);
<ide> }
<add>
<ide> return true;
<ide> }
<ide> $config = static::$_plugins[$plugin];
<ide> if ($config['routes'] === false) {
<ide> return false;
<ide> }
<add>
<ide> return (bool)static::_includeFile(
<ide> $config['configPath'] . 'routes.php',
<ide> $config['ignoreMissing']
<ide> public static function loaded($plugin = null)
<ide> }
<ide> $return = array_keys(static::$_plugins);
<ide> sort($return);
<add>
<ide> return $return;
<ide> }
<ide>
<ide> protected static function _includeFile($file, $ignoreMissing = false)
<ide> if ($ignoreMissing && !is_file($file)) {
<ide> return false;
<ide> }
<add>
<ide> return include $file;
<ide> }
<ide> }
<ide><path>src/Core/StaticConfigTrait.php
<ide> public static function config($key, $config = null)
<ide> foreach ($key as $name => $settings) {
<ide> static::config($name, $settings);
<ide> }
<add>
<ide> return;
<ide> }
<ide> }
<ide> public static function drop($config)
<ide> static::$_registry->unload($config);
<ide> }
<ide> unset(static::$_config[$config]);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function dsnClassMap(array $map = null)
<ide> if ($map !== null) {
<ide> static::$_dsnClassMap = $map + static::$_dsnClassMap;
<ide> }
<add>
<ide> return static::$_dsnClassMap;
<ide> }
<ide> }
<ide><path>src/Core/functions.php
<ide> function h($text, $double = true, $charset = null)
<ide> foreach ($text as $k => $t) {
<ide> $texts[$k] = h($t, $double, $charset);
<ide> }
<add>
<ide> return $texts;
<ide> } elseif (is_object($text)) {
<ide> if (method_exists($text, '__toString')) {
<ide> function h($text, $double = true, $charset = null)
<ide> if (is_string($double)) {
<ide> $charset = $double;
<ide> }
<add>
<ide> return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, ($charset) ? $charset : $defaultCharset, $double);
<ide> }
<ide>
<ide> function pluginSplit($name, $dotAppend = false, $plugin = null)
<ide> if ($dotAppend) {
<ide> $parts[0] .= '.';
<ide> }
<add>
<ide> return $parts;
<ide> }
<add>
<ide> return [$plugin, $name];
<ide> }
<ide>
<ide> function namespaceSplit($class)
<ide> if ($pos === false) {
<ide> return ['', $class];
<ide> }
<add>
<ide> return [substr($class, 0, $pos), substr($class, $pos + 1)];
<ide> }
<ide>
<ide> function env($key, $default = null)
<ide> if (isset($_SERVER['HTTPS'])) {
<ide> return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
<ide> }
<add>
<ide> return (strpos(env('SCRIPT_URI'), 'https://') === 0);
<ide> }
<ide>
<ide> function env($key, $default = null)
<ide> if (!strpos($name, '.php')) {
<ide> $offset = 4;
<ide> }
<add>
<ide> return substr($filename, 0, -(strlen($name) + $offset));
<ide> case 'PHP_SELF':
<ide> return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME'));
<ide> case 'CGI_MODE':
<ide> return (PHP_SAPI === 'cgi');
<ide> }
<add>
<ide> return $default;
<ide> }
<ide>
<ide><path>src/Database/Connection.php
<ide> public function configName()
<ide> if (empty($this->_config['name'])) {
<ide> return '';
<ide> }
<add>
<ide> return $this->_config['name'];
<ide> }
<ide>
<ide> public function driver($driver = null, $config = [])
<ide> if (!$driver->enabled()) {
<ide> throw new MissingExtensionException(['driver' => get_class($driver)]);
<ide> }
<add>
<ide> return $this->_driver = $driver;
<ide> }
<ide>
<ide> public function connect()
<ide> {
<ide> try {
<ide> $this->_driver->connect();
<add>
<ide> return true;
<ide> } catch (Exception $e) {
<ide> throw new MissingConnectionException(['reason' => $e->getMessage()]);
<ide> public function execute($query, array $params = [], array $types = [])
<ide> } else {
<ide> $statement = $this->query($query);
<ide> }
<add>
<ide> return $statement;
<ide> }
<ide>
<ide> public function query($sql)
<ide> {
<ide> $statement = $this->prepare($sql);
<ide> $statement->execute();
<add>
<ide> return $statement;
<ide> }
<ide>
<ide> public function schemaCollection(SchemaCollection $collection = null)
<ide> public function insert($table, array $data, array $types = [])
<ide> {
<ide> $columns = array_keys($data);
<add>
<ide> return $this->newQuery()->insert($columns, $types)
<ide> ->into($table)
<ide> ->values($data)
<ide> public function begin()
<ide> $this->_driver->beginTransaction();
<ide> $this->_transactionLevel = 0;
<ide> $this->_transactionStarted = true;
<add>
<ide> return;
<ide> }
<ide>
<ide> public function commit()
<ide> if ($this->_logQueries) {
<ide> $this->log('COMMIT');
<ide> }
<add>
<ide> return $this->_driver->commitTransaction();
<ide> }
<ide> if ($this->useSavePoints()) {
<ide> $this->releaseSavePoint($this->_transactionLevel);
<ide> }
<ide>
<ide> $this->_transactionLevel--;
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function rollback()
<ide> $this->log('ROLLBACK');
<ide> }
<ide> $this->_driver->rollbackTransaction();
<add>
<ide> return true;
<ide> }
<ide>
<ide> if ($useSavePoint) {
<ide> $this->rollbackSavepoint($this->_transactionLevel--);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function transactional(callable $callback)
<ide>
<ide> if ($result === false) {
<ide> $this->rollback();
<add>
<ide> return false;
<ide> }
<ide>
<ide> $this->commit();
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function disableConstraints(callable $callback)
<ide> }
<ide>
<ide> $this->enableForeignKeys();
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function inTransaction()
<ide> public function quote($value, $type = null)
<ide> {
<ide> list($value, $type) = $this->cast($value, $type);
<add>
<ide> return $this->_driver->quote($value, $type);
<ide> }
<ide>
<ide> public function logger($instance = null)
<ide> if ($this->_logger === null) {
<ide> $this->_logger = new QueryLogger;
<ide> }
<add>
<ide> return $this->_logger;
<ide> }
<ide> $this->_logger = $instance;
<ide> protected function _newLogger(StatementInterface $statement)
<ide> {
<ide> $log = new LoggingStatement($statement, $this->driver());
<ide> $log->logger($this->logger());
<add>
<ide> return $log;
<ide> }
<ide>
<ide><path>src/Database/Dialect/MysqlDialectTrait.php
<ide> public function schemaDialect()
<ide> if (!$this->_schemaDialect) {
<ide> $this->_schemaDialect = new MysqlSchema($this);
<ide> }
<add>
<ide> return $this->_schemaDialect;
<ide> }
<ide>
<ide><path>src/Database/Dialect/PostgresDialectTrait.php
<ide> protected function _insertQueryTranslator($query)
<ide> if (!$query->clause('epilog')) {
<ide> $query->epilog('RETURNING *');
<ide> }
<add>
<ide> return $query;
<ide> }
<ide>
<ide> protected function _insertQueryTranslator($query)
<ide> protected function _expressionTranslators()
<ide> {
<ide> $namespace = 'Cake\Database\Expression';
<add>
<ide> return [
<ide> $namespace . '\FunctionExpression' => '_transformFunctionExpression'
<ide> ];
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> if ($key === 1) {
<ide> $p = sprintf("'%s'", $p);
<ide> }
<add>
<ide> return $p;
<ide> });
<ide> break;
<ide> public function schemaDialect()
<ide> if (!$this->_schemaDialect) {
<ide> $this->_schemaDialect = new PostgresSchema($this);
<ide> }
<add>
<ide> return $this->_schemaDialect;
<ide> }
<ide>
<ide><path>src/Database/Dialect/SqliteDialectTrait.php
<ide> trait SqliteDialectTrait
<ide> protected function _expressionTranslators()
<ide> {
<ide> $namespace = 'Cake\Database\Expression';
<add>
<ide> return [
<ide> $namespace . '\FunctionExpression' => '_transformFunctionExpression',
<ide> $namespace . '\TupleComparison' => '_transformTupleComparison'
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> $p = ['value' => '%' . $this->_dateParts[$value], 'type' => null];
<ide> }
<ide> }
<add>
<ide> return $p;
<ide> });
<ide> break;
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> if ($key === 1) {
<ide> $p = ['value' => $p, 'type' => null];
<ide> }
<add>
<ide> return $p;
<ide> });
<ide> break;
<ide> public function schemaDialect()
<ide> if (!$this->_schemaDialect) {
<ide> $this->_schemaDialect = new SqliteSchema($this);
<ide> }
<add>
<ide> return $this->_schemaDialect;
<ide> }
<ide>
<ide><path>src/Database/Dialect/SqlserverDialectTrait.php
<ide> protected function _selectQueryTranslator($query)
<ide> public function _version()
<ide> {
<ide> $this->connect();
<add>
<ide> return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
<ide> }
<ide>
<ide> protected function _pagingSubquery($original, $limit, $offset)
<ide> if (isset($row['_cake_page_rownum_'])) {
<ide> unset($row['_cake_page_rownum_']);
<ide> }
<add>
<ide> return $row;
<ide> });
<ide>
<ide> protected function _transformDistinct($original)
<ide> ->add($order)
<ide> ->add(')')
<ide> ->tieWith(' ');
<add>
<ide> return [
<ide> '_cake_distinct_pivot_' => $over
<ide> ];
<ide> protected function _transformDistinct($original)
<ide> if (isset($row['_cake_distinct_pivot_'])) {
<ide> unset($row['_cake_distinct_pivot_']);
<ide> }
<add>
<ide> return $row;
<ide> });
<ide>
<ide> protected function _transformDistinct($original)
<ide> protected function _expressionTranslators()
<ide> {
<ide> $namespace = 'Cake\Database\Expression';
<add>
<ide> return [
<ide> $namespace . '\FunctionExpression' => '_transformFunctionExpression',
<ide> $namespace . '\TupleComparison' => '_transformTupleComparison'
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> if ($value === 'day') {
<ide> $hasDay = true;
<ide> }
<add>
<ide> return $value;
<ide> };
<ide> $expression->iterateParts($visitor);
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> $params[0] = rtrim($valueUnit[1], 's');
<ide> $params[1] = $valueUnit[0];
<ide> }
<add>
<ide> return $p;
<ide> };
<ide> $manipulator = function ($p, $key) use (&$params) {
<ide><path>src/Database/Dialect/TupleComparisonTranslatorTrait.php
<ide> protected function _transformTupleComparison(TupleComparison $expression, $query
<ide> $value->select($true, true);
<ide> $expression->setField($true);
<ide> $expression->setOperator('=');
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _transformTupleComparison(TupleComparison $expression, $query
<ide> foreach (array_values($tuple) as $i => $value) {
<ide> $exp->add([$fields[$i] => $value]);
<ide> }
<add>
<ide> return $exp;
<ide> });
<ide> }
<ide><path>src/Database/Driver.php
<ide> public function schemaValue($value)
<ide> ) {
<ide> return $value;
<ide> }
<add>
<ide> return $this->_connection->quote($value, PDO::PARAM_STR);
<ide> }
<ide>
<ide> public function autoQuoting($enable = null)
<ide> if ($enable === null) {
<ide> return $this->_autoQuoting;
<ide> }
<add>
<ide> return $this->_autoQuoting = (bool)$enable;
<ide> }
<ide>
<ide> public function compileQuery(Query $query, ValueBinder $generator)
<ide> $processor = $this->newCompiler();
<ide> $translator = $this->queryTranslator($query->type());
<ide> $query = $translator($query);
<add>
<ide> return [$query, $processor->compile($query, $generator)];
<ide> }
<ide>
<ide><path>src/Database/Driver/Mysql.php
<ide> public function connect()
<ide> $connection->exec($command);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function prepare($query)
<ide> if ($isObject && $query->bufferResults() === false) {
<ide> $result->bufferResults(false);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Database/Driver/PDODriverTrait.php
<ide> protected function _connect($dsn, array $config)
<ide> $config['flags']
<ide> );
<ide> $this->connection($connection);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function connection($connection = null)
<ide> if ($connection !== null) {
<ide> $this->_connection = $connection;
<ide> }
<add>
<ide> return $this->_connection;
<ide> }
<ide>
<ide> public function isConnected()
<ide> }
<ide> }
<ide> $this->connected = !empty($connected);
<add>
<ide> return $this->connected;
<ide> }
<ide>
<ide> public function prepare($query)
<ide> $this->connect();
<ide> $isObject = $query instanceof Query;
<ide> $statement = $this->_connection->prepare($isObject ? $query->sql() : $query);
<add>
<ide> return new PDOStatement($statement, $this);
<ide> }
<ide>
<ide> public function beginTransaction()
<ide> if ($this->_connection->inTransaction()) {
<ide> return true;
<ide> }
<add>
<ide> return $this->_connection->beginTransaction();
<ide> }
<ide>
<ide> public function commitTransaction()
<ide> if (!$this->_connection->inTransaction()) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_connection->commit();
<ide> }
<ide>
<ide> public function rollbackTransaction()
<ide> if (!$this->_connection->inTransaction()) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_connection->rollback();
<ide> }
<ide>
<ide> public function rollbackTransaction()
<ide> public function quote($value, $type)
<ide> {
<ide> $this->connect();
<add>
<ide> return $this->_connection->quote($value, $type);
<ide> }
<ide>
<ide> public function quote($value, $type)
<ide> public function lastInsertId($table = null, $column = null)
<ide> {
<ide> $this->connect();
<add>
<ide> return $this->_connection->lastInsertId($table);
<ide> }
<ide>
<ide> public function lastInsertId($table = null, $column = null)
<ide> public function supportsQuoting()
<ide> {
<ide> $this->connect();
<add>
<ide> return $this->_connection->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'odbc';
<ide> }
<ide> }
<ide><path>src/Database/Driver/Postgres.php
<ide> public function connect()
<ide> foreach ($config['init'] as $command) {
<ide> $connection->exec($command);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>src/Database/Driver/Sqlite.php
<ide> public function connect()
<ide> $this->connection()->exec($command);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function prepare($query)
<ide> if ($isObject && $query->bufferResults() === false) {
<ide> $result->bufferResults(false);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Database/Driver/Sqlserver.php
<ide> public function connect()
<ide> $connection->exec("SET {$key} {$value}");
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function prepare($query)
<ide> $options = [];
<ide> }
<ide> $statement = $this->_connection->prepare($isObject ? $query->sql() : $query, $options);
<add>
<ide> return new SqlserverStatement($statement, $this);
<ide> }
<ide>
<ide><path>src/Database/Expression/BetweenExpression.php
<ide> protected function _bindValue($value, $generator, $type)
<ide> {
<ide> $placeholder = $generator->placeholder('c');
<ide> $generator->bind($placeholder, $value, $type);
<add>
<ide> return $placeholder;
<ide> }
<ide>
<ide><path>src/Database/Expression/Comparison.php
<ide> protected function _bindValue($value, $generator, $type)
<ide> {
<ide> $placeholder = $generator->placeholder('c');
<ide> $generator->bind($placeholder, $value, $type);
<add>
<ide> return $placeholder;
<ide> }
<ide>
<ide><path>src/Database/Expression/FunctionExpression.php
<ide> public function name($name = null)
<ide> return $this->_name;
<ide> }
<ide> $this->_name = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function sql(ValueBinder $generator)
<ide> }
<ide> $parts[] = $condition;
<ide> }
<add>
<ide> return $this->_name . sprintf('(%s)', implode(
<ide> $this->_conjunction . ' ',
<ide> $parts
<ide><path>src/Database/Expression/OrderByExpression.php
<ide> public function sql(ValueBinder $generator)
<ide> }
<ide> $order[] = is_numeric($k) ? $direction : sprintf('%s %s', $k, $direction);
<ide> }
<add>
<ide> return sprintf('ORDER BY %s', implode(', ', $order));
<ide> }
<ide>
<ide><path>src/Database/Expression/OrderClauseExpression.php
<ide> public function sql(ValueBinder $generator)
<ide> if ($field instanceof ExpressionInterface) {
<ide> $field = $field->sql($generator);
<ide> }
<add>
<ide> return sprintf("%s %s", $field, $this->_direction);
<ide> }
<ide>
<ide><path>src/Database/Expression/QueryExpression.php
<ide> public function tieWith($conjunction = null)
<ide> }
<ide>
<ide> $this->_conjunction = strtoupper($conjunction);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function add($conditions, $types = [])
<ide> {
<ide> if (is_string($conditions)) {
<ide> $this->_conditions[] = $conditions;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> if ($conditions instanceof ExpressionInterface) {
<ide> $this->_conditions[] = $conditions;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> $this->_addConditions($conditions, $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function eq($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '='));
<ide> }
<ide>
<ide> public function notEq($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '!='));
<ide> }
<ide>
<ide> public function gt($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '>'));
<ide> }
<ide>
<ide> public function lt($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '<'));
<ide> }
<ide>
<ide> public function gte($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '>='));
<ide> }
<ide>
<ide> public function lte($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, '<='));
<ide> }
<ide>
<ide> public function isNull($field)
<ide> if (!($field instanceof ExpressionInterface)) {
<ide> $field = new IdentifierExpression($field);
<ide> }
<add>
<ide> return $this->add(new UnaryExpression('IS NULL', $field, UnaryExpression::POSTFIX));
<ide> }
<ide>
<ide> public function isNotNull($field)
<ide> if (!($field instanceof ExpressionInterface)) {
<ide> $field = new IdentifierExpression($field);
<ide> }
<add>
<ide> return $this->add(new UnaryExpression('IS NOT NULL', $field, UnaryExpression::POSTFIX));
<ide> }
<ide>
<ide> public function like($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, 'LIKE'));
<ide> }
<ide>
<ide> public function notLike($field, $value, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new Comparison($field, $value, $type, 'NOT LIKE'));
<ide> }
<ide>
<ide> public function in($field, $values, $type = null)
<ide> $type = $type ?: 'string';
<ide> $type .= '[]';
<ide> $values = $values instanceof ExpressionInterface ? $values : (array)$values;
<add>
<ide> return $this->add(new Comparison($field, $values, $type, 'IN'));
<ide> }
<ide>
<ide> public function notIn($field, $values, $type = null)
<ide> $type = $type ?: 'string';
<ide> $type .= '[]';
<ide> $values = $values instanceof ExpressionInterface ? $values : (array)$values;
<add>
<ide> return $this->add(new Comparison($field, $values, $type, 'NOT IN'));
<ide> }
<ide>
<ide> public function between($field, $from, $to, $type = null)
<ide> if ($type === null) {
<ide> $type = $this->_calculateType($field);
<ide> }
<add>
<ide> return $this->add(new BetweenExpression($field, $from, $to, $type));
<ide> }
<ide>
<ide> public function and_($conditions, $types = [])
<ide> if ($this->isCallable($conditions)) {
<ide> return $conditions(new self([], $this->typeMap()->types($types)));
<ide> }
<add>
<ide> return new self($conditions, $this->typeMap()->types($types));
<ide> }
<ide>
<ide> public function or_($conditions, $types = [])
<ide> if ($this->isCallable($conditions)) {
<ide> return $conditions(new self([], $this->typeMap()->types($types), 'OR'));
<ide> }
<add>
<ide> return new self($conditions, $this->typeMap()->types($types), 'OR');
<ide> }
<ide> // @codingStandardsIgnoreEnd
<ide> public function equalFields($left, $right)
<ide> if ($field instanceof ExpressionInterface) {
<ide> return $field;
<ide> }
<add>
<ide> return new IdentifierExpression($field);
<ide> };
<add>
<ide> return $this->eq($wrapIdentifier($left), $wrapIdentifier($right));
<ide> }
<ide>
<ide> public function sql(ValueBinder $generator)
<ide> $parts[] = $part;
<ide> }
<ide> }
<add>
<ide> return sprintf($template, implode(" $conjunction ", $parts));
<ide> }
<ide>
<ide> public function isCallable($c)
<ide> if (is_object($c) && is_callable($c)) {
<ide> return true;
<ide> }
<add>
<ide> return is_array($c) && isset($c[0]) && is_object($c[0]) && is_callable($c);
<ide> }
<ide>
<ide> public function hasNestedExpression()
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _calculateType($field)
<ide> if (is_string($field)) {
<ide> return $this->typeMap()->type($field);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>src/Database/Expression/TupleComparison.php
<ide> public function sql(ValueBinder $generator)
<ide> $values = $this->_stringifyValues($generator);
<ide>
<ide> $field = implode(', ', $fields);
<add>
<ide> return sprintf($template, $field, $this->_operator, $values);
<ide> }
<ide>
<ide> protected function _bindValue($generator, $value, $type)
<ide> {
<ide> $placeholder = $generator->placeholder('tuple');
<ide> $generator->bind($placeholder, $value, $type);
<add>
<ide> return $placeholder;
<ide> }
<ide>
<ide> public function traverse(callable $callable)
<ide> if ($value instanceof ExpressionInterface) {
<ide> $callable($value);
<ide> $value->traverse($callable);
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function add($data)
<ide> }
<ide> if ($data instanceof Query) {
<ide> $this->query($data);
<add>
<ide> return;
<ide> }
<ide> $this->_values[] = $data;
<ide> public function columns($cols = null)
<ide> return $this->_columns;
<ide> }
<ide> $this->_columns = $cols;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function values($values = null)
<ide> return $this->_values;
<ide> }
<ide> $this->_values = $values;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function sql(ValueBinder $generator)
<ide> if ($this->query()) {
<ide> return ' ' . $this->query()->sql($generator);
<ide> }
<add>
<ide> return sprintf(' VALUES (%s)', implode('), (', $placeholders));
<ide> }
<ide>
<ide><path>src/Database/FieldTypeConverter.php
<ide> public function __invoke($row)
<ide> foreach ($this->_typeMap as $field => $type) {
<ide> $row[$field] = $type->toPHP($row[$field], $this->_driver);
<ide> }
<add>
<ide> return $row;
<ide> }
<ide> }
<ide><path>src/Database/FunctionsBuilder.php
<ide> protected function _literalArgumentFunction($name, $expression, $types = [], $re
<ide> } else {
<ide> $expression = [$expression => 'literal'];
<ide> }
<add>
<ide> return $this->_build($name, $expression, $types, $return);
<ide> }
<ide>
<ide> public function sum($expression, $types = [])
<ide> if (current($types) === 'integer') {
<ide> $returnType = 'integer';
<ide> }
<add>
<ide> return $this->_literalArgumentFunction('SUM', $expression, $types, $returnType);
<ide> }
<ide>
<ide> public function extract($part, $expression, $types = [])
<ide> {
<ide> $expression = $this->_literalArgumentFunction('EXTRACT', $expression, $types, 'integer');
<ide> $expression->tieWith(' FROM')->add([$part => 'literal'], [], true);
<add>
<ide> return $expression;
<ide> }
<ide>
<ide> public function dateAdd($expression, $value, $unit, $types = [])
<ide> $interval = $value . ' ' . $unit;
<ide> $expression = $this->_literalArgumentFunction('DATE_ADD', $expression, $types, 'datetime');
<ide> $expression->tieWith(', INTERVAL')->add([$interval => 'literal']);
<add>
<ide> return $expression;
<ide> }
<ide>
<ide><path>src/Database/IdentifierQuoter.php
<ide> public function quote(Query $query)
<ide>
<ide> $query->traverseExpressions([$this, 'quoteExpression']);
<ide> $query->valueBinder($binder);
<add>
<ide> return $query;
<ide> }
<ide>
<ide> public function quoteExpression($expression)
<ide> {
<ide> if ($expression instanceof FieldInterface) {
<ide> $this->_quoteComparison($expression);
<add>
<ide> return;
<ide> }
<ide>
<ide> if ($expression instanceof OrderByExpression) {
<ide> $this->_quoteOrderBy($expression);
<add>
<ide> return;
<ide> }
<ide>
<ide> if ($expression instanceof IdentifierExpression) {
<ide> $this->_quoteIdentifierExpression($expression);
<add>
<ide> return;
<ide> }
<ide> }
<ide> protected function _basicQuoter($part)
<ide> $alias = is_numeric($alias) ? $alias : $this->_driver->quoteIdentifier($alias);
<ide> $result[$alias] = $value;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> protected function _quoteOrderBy(OrderByExpression $expression)
<ide> $expression->iterateParts(function ($part, &$field) {
<ide> if (is_string($field)) {
<ide> $field = $this->_driver->quoteIdentifier($field);
<add>
<ide> return $part;
<ide> }
<ide> if (is_string($part) && strpos($part, ' ') === false) {
<ide> return $this->_driver->quoteIdentifier($part);
<ide> }
<add>
<ide> return $part;
<ide> });
<ide> }
<ide><path>src/Database/Log/LoggingStatement.php
<ide> public function execute($params = null)
<ide>
<ide> $query->numRows = $this->rowCount();
<ide> $this->_log($query, $params, $t);
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function logger($instance = null)
<ide> if ($instance === null) {
<ide> return $this->_logger;
<ide> }
<add>
<ide> return $this->_logger = $instance;
<ide> }
<ide> }
<ide><path>src/Database/Log/QueryLogger.php
<ide> protected function _interpolate($query)
<ide> if (is_bool($p)) {
<ide> return $p ? '1' : '0';
<ide> }
<add>
<ide> return is_string($p) ? "'$p'" : $p;
<ide> }, $query->params);
<ide>
<ide><path>src/Database/Query.php
<ide> public function connection($connection = null)
<ide> }
<ide> $this->_dirty();
<ide> $this->_connection = $connection;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function execute()
<ide>
<ide> $this->_iterator = $this->_decorateStatement($statement);
<ide> $this->_dirty = false;
<add>
<ide> return $this->_iterator;
<ide> }
<ide>
<ide> public function traverse(callable $visitor, array $parts = [])
<ide> foreach ($parts as $name) {
<ide> $visitor($this->_parts[$name], $name);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function select($fields = [], $overwrite = false)
<ide>
<ide> $this->_dirty();
<ide> $this->_type = 'select';
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function distinct($on = [], $overwrite = false)
<ide>
<ide> $this->_parts['distinct'] = $on;
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function modifier($modifiers, $overwrite = false)
<ide> $this->_parts['modifier'] = [];
<ide> }
<ide> $this->_parts['modifier'] = array_merge($this->_parts['modifier'], (array)$modifiers);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function from($tables = [], $overwrite = false)
<ide> }
<ide>
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function join($tables = null, $types = [], $overwrite = false)
<ide> }
<ide>
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function removeJoin($name)
<ide> {
<ide> unset($this->_parts['join'][$name]);
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function where($conditions = null, $types = [], $overwrite = false)
<ide> $this->_parts['where'] = $this->newExpr();
<ide> }
<ide> $this->_conjugate('where', $conditions, 'AND', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function where($conditions = null, $types = [], $overwrite = false)
<ide> public function andWhere($conditions, $types = [])
<ide> {
<ide> $this->_conjugate('where', $conditions, 'AND', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function andWhere($conditions, $types = [])
<ide> public function orWhere($conditions, $types = [])
<ide> {
<ide> $this->_conjugate('where', $conditions, 'OR', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function order($fields, $overwrite = false)
<ide> $this->_parts['order'] = new OrderByExpression();
<ide> }
<ide> $this->_conjugate('order', $fields, '', []);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function orderAsc($field, $overwrite = false)
<ide> $this->_parts['order'] = new OrderByExpression();
<ide> }
<ide> $this->_parts['order']->add(new OrderClauseExpression($field, 'ASC'));
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function orderDesc($field, $overwrite = false)
<ide> $this->_parts['order'] = new OrderByExpression();
<ide> }
<ide> $this->_parts['order']->add(new OrderClauseExpression($field, 'DESC'));
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function group($fields, $overwrite = false)
<ide>
<ide> $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields));
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function having($conditions = null, $types = [], $overwrite = false)
<ide> $this->_parts['having'] = $this->newExpr();
<ide> }
<ide> $this->_conjugate('having', $conditions, 'AND', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function having($conditions = null, $types = [], $overwrite = false)
<ide> public function andHaving($conditions, $types = [])
<ide> {
<ide> $this->_conjugate('having', $conditions, 'AND', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function andHaving($conditions, $types = [])
<ide> public function orHaving($conditions, $types = [])
<ide> {
<ide> $this->_conjugate('having', $conditions, 'OR', $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function page($num, $limit = null)
<ide> $offset = PHP_INT_MAX;
<ide> }
<ide> $this->offset((int)$offset);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function limit($num)
<ide> $num = (int)$num;
<ide> }
<ide> $this->_parts['limit'] = $num;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function offset($num)
<ide> $num = (int)$num;
<ide> }
<ide> $this->_parts['offset'] = $num;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function union($query, $overwrite = false)
<ide> 'query' => $query
<ide> ];
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function unionAll($query, $overwrite = false)
<ide> 'query' => $query
<ide> ];
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function insert(array $columns, array $types = [])
<ide> } else {
<ide> $this->_parts['values']->columns($columns);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function into($table)
<ide> $this->_dirty();
<ide> $this->_type = 'insert';
<ide> $this->_parts['insert'][0] = $table;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function values($data)
<ide> $this->_dirty();
<ide> if ($data instanceof ValuesExpression) {
<ide> $this->_parts['values'] = $data;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> $this->_parts['values']->add($data);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function update($table)
<ide> $this->_dirty();
<ide> $this->_type = 'update';
<ide> $this->_parts['update'][0] = $table;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function set($key, $value = null, $types = [])
<ide> if ($this->_parts['set']->isCallable($key)) {
<ide> $exp = $this->newExpr()->tieWith(',');
<ide> $this->_parts['set']->add($key($exp));
<add>
<ide> return $this;
<ide> }
<ide>
<ide> if (is_array($key) || $key instanceof ExpressionInterface) {
<ide> $types = (array)$value;
<ide> $this->_parts['set']->add($key, $types);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function delete($table = null)
<ide> if ($table !== null) {
<ide> $this->from($table);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function epilog($expression = null)
<ide> {
<ide> $this->_dirty();
<ide> $this->_parts['epilog'] = $expression;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function func()
<ide> if (empty($this->_functionsBuilder)) {
<ide> $this->_functionsBuilder = new FunctionsBuilder;
<ide> }
<add>
<ide> return $this->_functionsBuilder;
<ide> }
<ide>
<ide> public function getIterator()
<ide> if (empty($this->_iterator) || $this->_dirty) {
<ide> $this->_iterator = $this->execute();
<ide> }
<add>
<ide> return $this->_iterator;
<ide> }
<ide>
<ide> public function traverseExpressions(callable $callback)
<ide> foreach ($expression as $e) {
<ide> $visitor($e);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function traverseExpressions(callable $callback)
<ide> }
<ide> }
<ide> };
<add>
<ide> return $this->traverse($visitor);
<ide> }
<ide>
<ide> public function traverseExpressions(callable $callback)
<ide> public function bind($param, $value, $type = 'string')
<ide> {
<ide> $this->valueBinder()->bind($param, $value, $type);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function valueBinder($binder = null)
<ide> if ($this->_valueBinder === null) {
<ide> $this->_valueBinder = new ValueBinder;
<ide> }
<add>
<ide> return $this->_valueBinder;
<ide> }
<ide> $this->_valueBinder = $binder;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function bufferResults($enable = null)
<ide>
<ide> $this->_dirty();
<ide> $this->_useBufferedResults = (bool)$enable;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function selectTypeMap(TypeMap $typeMap = null)
<ide> }
<ide>
<ide> $this->_selectTypeMap = $typeMap;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _decorateStatement($statement)
<ide> foreach ($this->_resultDecorators as $f) {
<ide> $statement = new CallbackStatement($statement, $this->connection()->driver(), $f);
<ide> }
<add>
<ide> return $statement;
<ide> }
<ide>
<ide> protected function _conjugate($part, $append, $conjunction, $types)
<ide> $expression = $this->_parts[$part] ?: $this->newExpr();
<ide> if (empty($append)) {
<ide> $this->_parts[$part] = $expression;
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/Database/QueryCompiler.php
<ide> public function compile(Query $query, ValueBinder $generator)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $sql;
<ide> }
<ide>
<ide> protected function _sqlCompiler(&$sql, $query, $generator)
<ide> }
<ide> if (isset($this->_templates[$name])) {
<ide> $parts = $this->_stringifyExpressions((array)$parts, $generator);
<add>
<ide> return $sql .= sprintf($this->_templates[$name], implode(', ', $parts));
<ide> }
<add>
<ide> return $sql .= $this->{'_build' . ucfirst($name) . 'Part'}($parts, $query, $generator);
<ide> };
<ide> }
<ide> protected function _buildFromPart($parts, $query, $generator)
<ide> }
<ide> $normalized[] = $p;
<ide> }
<add>
<ide> return sprintf($select, implode(', ', $normalized));
<ide> }
<ide>
<ide> protected function _buildJoinPart($parts, $query, $generator)
<ide> $joins .= ' ON 1 = 1';
<ide> }
<ide> }
<add>
<ide> return $joins;
<ide> }
<ide>
<ide> protected function _buildSetPart($parts, $query, $generator)
<ide> }
<ide> $set[] = $part;
<ide> }
<add>
<ide> return ' SET ' . implode('', $set);
<ide> }
<ide>
<ide> protected function _buildUnionPart($parts, $query, $generator)
<ide> if ($this->_orderedUnion) {
<ide> return "{$prefix}({$p['query']})";
<ide> }
<add>
<ide> return $prefix . $p['query'];
<ide> }, $parts);
<ide>
<ide> if ($this->_orderedUnion) {
<ide> return sprintf(")\nUNION %s", implode("\nUNION ", $parts));
<ide> }
<add>
<ide> return sprintf("\nUNION %s", implode("\nUNION ", $parts));
<ide> }
<ide>
<ide> protected function _buildInsertPart($parts, $query, $generator)
<ide> {
<ide> $table = $parts[0];
<ide> $columns = $this->_stringifyExpressions($parts[1], $generator);
<add>
<ide> return sprintf('INSERT INTO %s (%s)', $table, implode(', ', $columns));
<ide> }
<ide>
<ide> protected function _stringifyExpressions($expressions, $generator)
<ide> }
<ide> $result[$k] = $expression;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>src/Database/Schema/BaseSchema.php
<ide> protected function _convertOnClause($clause)
<ide> if ($clause === 'NO ACTION') {
<ide> return Table::ACTION_NO_ACTION;
<ide> }
<add>
<ide> return Table::ACTION_SET_NULL;
<ide> }
<ide>
<ide> public function dropTableSql(Table $table)
<ide> 'DROP TABLE %s',
<ide> $this->_driver->quoteIdentifier($table->name())
<ide> );
<add>
<ide> return [$sql];
<ide> }
<ide>
<ide><path>src/Database/Schema/CachedCollection.php
<ide> public function cacheMetadata($enable = null)
<ide> if ($enable === true) {
<ide> $enable = '_cake_model_';
<ide> }
<add>
<ide> return $this->_cache = $enable;
<ide> }
<ide> }
<ide><path>src/Database/Schema/Collection.php
<ide> public function listTables()
<ide> $result[] = $row[0];
<ide> }
<ide> $statement->closeCursor();
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> protected function _convertColumn($column)
<ide> if (strpos($col, 'text') !== false) {
<ide> $lengthName = substr($col, 0, -4);
<ide> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<add>
<ide> return ['type' => 'text', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'blob') !== false || $col === 'binary') {
<ide> $lengthName = substr($col, 0, -4);
<ide> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<add>
<ide> return ['type' => 'binary', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
<ide> protected function _convertColumn($column)
<ide> 'unsigned' => $unsigned
<ide> ];
<ide> }
<add>
<ide> return ['type' => 'text', 'length' => null];
<ide> }
<ide>
<ide> public function createTableSql(Table $table, $columns, $constraints, $indexes)
<ide> if (isset($options['collate'])) {
<ide> $content .= sprintf(' COLLATE=%s', $options['collate']);
<ide> }
<add>
<ide> return [$content];
<ide> }
<ide>
<ide> public function columnSql(Table $table, $name)
<ide> if (isset($data['comment']) && $data['comment'] !== '') {
<ide> $out .= ' COMMENT ' . $this->_driver->schemaValue($data['comment']);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function constraintSql(Table $table, $name)
<ide> [$this->_driver, 'quoteIdentifier'],
<ide> $data['columns']
<ide> );
<add>
<ide> return sprintf('PRIMARY KEY (%s)', implode(', ', $columns));
<ide> }
<ide>
<ide> public function constraintSql(Table $table, $name)
<ide> $out = 'CONSTRAINT ';
<ide> }
<ide> $out .= $this->_driver->quoteIdentifier($name);
<add>
<ide> return $this->_keySql($out, $data);
<ide> }
<ide>
<ide> public function indexSql(Table $table, $name)
<ide> $out = 'FULLTEXT KEY ';
<ide> }
<ide> $out .= $this->_driver->quoteIdentifier($name);
<add>
<ide> return $this->_keySql($out, $data);
<ide> }
<ide>
<ide> protected function _keySql($prefix, $data)
<ide> $this->_foreignOnClause($data['delete'])
<ide> );
<ide> }
<add>
<ide> return $prefix . ' (' . implode(', ', $columns) . ')';
<ide> }
<ide> }
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> public function listTablesSql($config)
<ide> {
<ide> $sql = 'SELECT table_name as name FROM information_schema.tables WHERE table_schema = ? ORDER BY name';
<ide> $schema = empty($config['schema']) ? 'public' : $config['schema'];
<add>
<ide> return [$sql, [$schema]];
<ide> }
<ide>
<ide> public function describeColumnSql($tableName, $config)
<ide> ORDER BY ordinal_position';
<ide>
<ide> $schema = empty($config['schema']) ? 'public' : $config['schema'];
<add>
<ide> return [$sql, [$tableName, $schema, $config['database']]];
<ide> }
<ide>
<ide> protected function _convertColumn($column)
<ide> ) {
<ide> return ['type' => 'decimal', 'length' => null];
<ide> }
<add>
<ide> return ['type' => 'text', 'length' => null];
<ide> }
<ide>
<ide> public function describeIndexSql($tableName, $config)
<ide> if (!empty($config['schema'])) {
<ide> $schema = $config['schema'];
<ide> }
<add>
<ide> return [$sql, [$schema, $tableName]];
<ide> }
<ide>
<ide> public function convertIndexDescription(Table $table, $row)
<ide> }
<ide> if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) {
<ide> $this->_convertConstraint($table, $name, $type, $row);
<add>
<ide> return;
<ide> }
<ide> $index = $table->index($name);
<ide> public function describeForeignKeySql($tableName, $config)
<ide> ORDER BY name, a.attnum, ab.attnum DESC";
<ide>
<ide> $schema = empty($config['schema']) ? 'public' : $config['schema'];
<add>
<ide> return [$sql, [$schema, $tableName]];
<ide> }
<ide>
<ide> protected function _convertOnClause($clause)
<ide> if ($clause === 'c') {
<ide> return Table::ACTION_CASCADE;
<ide> }
<add>
<ide> return Table::ACTION_SET_NULL;
<ide> }
<ide>
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide> $out .= ' DEFAULT ' . $this->_driver->schemaValue($defaultValue);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function indexSql(Table $table, $name)
<ide> [$this->_driver, 'quoteIdentifier'],
<ide> $data['columns']
<ide> );
<add>
<ide> return sprintf(
<ide> 'CREATE INDEX %s ON %s (%s)',
<ide> $this->_driver->quoteIdentifier($name),
<ide> public function constraintSql(Table $table, $name)
<ide> if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
<ide> $out .= ' UNIQUE';
<ide> }
<add>
<ide> return $this->_keySql($out, $data);
<ide> }
<ide>
<ide> protected function _keySql($prefix, $data)
<ide> $this->_foreignOnClause($data['delete'])
<ide> );
<ide> }
<add>
<ide> return $prefix . ' (' . implode(', ', $columns) . ')';
<ide> }
<ide>
<ide> public function createTableSql(Table $table, $columns, $constraints, $indexes)
<ide> );
<ide> }
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function createTableSql(Table $table, $columns, $constraints, $indexes)
<ide> public function truncateTableSql(Table $table)
<ide> {
<ide> $name = $this->_driver->quoteIdentifier($table->name());
<add>
<ide> return [
<ide> sprintf('TRUNCATE %s RESTART IDENTITY CASCADE', $name)
<ide> ];
<ide> public function dropTableSql(Table $table)
<ide> 'DROP TABLE %s CASCADE',
<ide> $this->_driver->quoteIdentifier($table->name())
<ide> );
<add>
<ide> return [$sql];
<ide> }
<ide> }
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function describeColumnSql($tableName, $config)
<ide> 'PRAGMA table_info(%s)',
<ide> $this->_driver->quoteIdentifier($tableName)
<ide> );
<add>
<ide> return [$sql, []];
<ide> }
<ide>
<ide> public function describeIndexSql($tableName, $config)
<ide> 'PRAGMA index_list(%s)',
<ide> $this->_driver->quoteIdentifier($tableName)
<ide> );
<add>
<ide> return [$sql, []];
<ide> }
<ide>
<ide> public function convertIndexDescription(Table $table, $row)
<ide> public function describeForeignKeySql($tableName, $config)
<ide> {
<ide> $sql = sprintf('PRAGMA foreign_key_list(%s)', $this->_driver->quoteIdentifier($tableName));
<add>
<ide> return [$sql, []];
<ide> }
<ide>
<ide> public function columnSql(Table $table, $name)
<ide> if (isset($data['default'])) {
<ide> $out .= ' DEFAULT ' . $this->_driver->schemaValue($data['default']);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function constraintSql(Table $table, $name)
<ide> [$this->_driver, 'quoteIdentifier'],
<ide> $data['columns']
<ide> );
<add>
<ide> return sprintf(
<ide> 'CONSTRAINT %s %s (%s)%s',
<ide> $this->_driver->quoteIdentifier($name),
<ide> public function indexSql(Table $table, $name)
<ide> [$this->_driver, 'quoteIdentifier'],
<ide> $data['columns']
<ide> );
<add>
<ide> return sprintf(
<ide> 'CREATE INDEX %s ON %s (%s)',
<ide> $this->_driver->quoteIdentifier($name),
<ide> public function createTableSql(Table $table, $columns, $constraints, $indexes)
<ide> foreach ($indexes as $index) {
<ide> $out[] = $index;
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function truncateTableSql(Table $table)
<ide> }
<ide>
<ide> $sql[] = sprintf('DELETE FROM "%s"', $name);
<add>
<ide> return $sql;
<ide> }
<ide>
<ide> public function hasSequences()
<ide> $result->execute();
<ide> $this->_hasSequences = (bool)$result->rowCount();
<ide> $result->closeCursor();
<add>
<ide> return $this->_hasSequences;
<ide> }
<ide> }
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function listTablesSql($config)
<ide> AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW')
<ide> ORDER BY TABLE_NAME";
<ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
<add>
<ide> return [$sql, [$schema]];
<ide> }
<ide>
<ide> public function describeColumnSql($tableName, $config)
<ide> ORDER BY column_id";
<ide>
<ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
<add>
<ide> return [$sql, [$tableName, $schema]];
<ide> }
<ide>
<ide> public function describeIndexSql($tableName, $config)
<ide> ORDER BY I.[index_id], IC.[index_column_id]";
<ide>
<ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
<add>
<ide> return [$sql, [$tableName, $schema]];
<ide> }
<ide>
<ide> public function convertIndexDescription(Table $table, $row)
<ide> 'type' => $type,
<ide> 'columns' => $columns
<ide> ]);
<add>
<ide> return;
<ide> }
<ide> $table->addIndex($name, [
<ide> public function describeForeignKeySql($tableName, $config)
<ide> WHERE FK.is_ms_shipped = 0 AND T.name = ? AND S.name = ?";
<ide>
<ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema'];
<add>
<ide> return [$sql, [$tableName, $schema]];
<ide> }
<ide>
<ide> public function convertForeignKeyDescription(Table $table, $row)
<ide> protected function _foreignOnClause($on)
<ide> {
<ide> $parent = parent::_foreignOnClause($on);
<add>
<ide> return $parent === 'RESTRICT' ? parent::_foreignOnClause(Table::ACTION_SET_NULL) : $parent;
<ide> }
<ide>
<ide> protected function _convertOnClause($clause)
<ide> case 'SET_DEFAULT':
<ide> return Table::ACTION_SET_DEFAULT;
<ide> }
<add>
<ide> return Table::ACTION_SET_NULL;
<ide> }
<ide>
<ide> public function indexSql(Table $table, $name)
<ide> [$this->_driver, 'quoteIdentifier'],
<ide> $data['columns']
<ide> );
<add>
<ide> return sprintf(
<ide> 'CREATE INDEX %s ON %s (%s)',
<ide> $this->_driver->quoteIdentifier($name),
<ide> public function constraintSql(Table $table, $name)
<ide> if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
<ide> $out .= ' UNIQUE';
<ide> }
<add>
<ide> return $this->_keySql($out, $data);
<ide> }
<ide>
<ide> protected function _keySql($prefix, $data)
<ide> $this->_foreignOnClause($data['delete'])
<ide> );
<ide> }
<add>
<ide> return $prefix . ' (' . implode(', ', $columns) . ')';
<ide> }
<ide>
<ide> public function createTableSql(Table $table, $columns, $constraints, $indexes)
<ide> foreach ($indexes as $index) {
<ide> $out[] = $index;
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function truncateTableSql(Table $table)
<ide> );
<ide> }
<ide> }
<add>
<ide> return $queries;
<ide> }
<ide> }
<ide><path>src/Database/Schema/Table.php
<ide> public function addColumn($name, $attrs)
<ide> $attrs = array_intersect_key($attrs, $valid);
<ide> $this->_columns[$name] = $attrs + $valid;
<ide> $this->_typeMap[$name] = $this->_columns[$name]['type'];
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function column($name)
<ide> }
<ide> $column = $this->_columns[$name];
<ide> unset($column['baseType']);
<add>
<ide> return $column;
<ide> }
<ide>
<ide> public function columnType($name, $type = null)
<ide> $this->_columns[$name]['type'] = $type;
<ide> $this->_typeMap[$name] = $type;
<ide> }
<add>
<ide> return $this->_columns[$name]['type'];
<ide> }
<ide>
<ide> public function baseColumnType($column)
<ide> if (Type::map($type)) {
<ide> $type = Type::build($type)->getBaseType();
<ide> }
<add>
<ide> return $this->_columns[$column]['baseType'] = $type;
<ide> }
<ide>
<ide> public function isNullable($name)
<ide> if (!isset($this->_columns[$name])) {
<ide> return true;
<ide> }
<add>
<ide> return ($this->_columns[$name]['null'] === true);
<ide> }
<ide>
<ide> public function defaultValues()
<ide> }
<ide> $defaults[$name] = $data['default'];
<ide> }
<add>
<ide> return $defaults;
<ide> }
<ide>
<ide> public function addIndex($name, $attrs)
<ide> }
<ide> }
<ide> $this->_indexes[$name] = $attrs;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function index($name)
<ide> if (!isset($this->_indexes[$name])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->_indexes[$name];
<ide> }
<ide>
<ide> public function primaryKey()
<ide> return $data['columns'];
<ide> }
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> public function addConstraint($name, $attrs)
<ide> [$attrs['references'][1]]
<ide> ));
<ide> }
<add>
<ide> return $this;
<ide> }
<ide> } else {
<ide> unset($attrs['references'], $attrs['update'], $attrs['delete']);
<ide> }
<ide>
<ide> $this->_constraints[$name] = $attrs;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function hasAutoincrement()
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _checkForeignKey($attrs)
<ide> if (!in_array($attrs['delete'], static::$_validForeignKeyActions)) {
<ide> throw new Exception(sprintf('Delete action is invalid. Must be one of %s', implode(',', static::$_validForeignKeyActions)));
<ide> }
<add>
<ide> return $attrs;
<ide> }
<ide>
<ide> public function constraint($name)
<ide> if (!isset($this->_constraints[$name])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->_constraints[$name];
<ide> }
<ide>
<ide> public function options($options = null)
<ide> return $this->_options;
<ide> }
<ide> $this->_options = array_merge($this->_options, $options);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function temporary($set = null)
<ide> return $this->_temporary;
<ide> }
<ide> $this->_temporary = (bool)$set;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function createSql(ConnectionInterface $connection)
<ide> foreach (array_keys($this->_indexes) as $name) {
<ide> $indexes[] = $dialect->indexSql($this, $name);
<ide> }
<add>
<ide> return $dialect->createTableSql($this, $columns, $constraints, $indexes);
<ide> }
<ide>
<ide> public function createSql(ConnectionInterface $connection)
<ide> public function dropSql(ConnectionInterface $connection)
<ide> {
<ide> $dialect = $connection->driver()->schemaDialect();
<add>
<ide> return $dialect->dropTableSql($this);
<ide> }
<ide>
<ide> public function dropSql(ConnectionInterface $connection)
<ide> public function truncateSql(ConnectionInterface $connection)
<ide> {
<ide> $dialect = $connection->driver()->schemaDialect();
<add>
<ide> return $dialect->truncateTableSql($this);
<ide> }
<ide>
<ide> public function truncateSql(ConnectionInterface $connection)
<ide> public function addConstraintSql(ConnectionInterface $connection)
<ide> {
<ide> $dialect = $connection->driver()->schemaDialect();
<add>
<ide> return $dialect->addConstraintSql($this);
<ide> }
<ide>
<ide> public function addConstraintSql(ConnectionInterface $connection)
<ide> public function dropConstraintSql(ConnectionInterface $connection)
<ide> {
<ide> $dialect = $connection->driver()->schemaDialect();
<add>
<ide> return $dialect->dropConstraintSql($this);
<ide> }
<ide> }
<ide><path>src/Database/SqlDialectTrait.php
<ide> public function quoteIdentifier($identifier)
<ide> if (preg_match('/^[\w-]+\.[^ \*]*$/', $identifier)) {
<ide> // string.string
<ide> $items = explode('.', $identifier);
<add>
<ide> return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
<ide> }
<ide>
<ide> public function queryTranslator($type)
<ide> }
<ide> }
<ide> });
<add>
<ide> return $query;
<ide> };
<ide> }
<ide> protected function _transformDistinct($query)
<ide> $query->group($query->clause('distinct'), true);
<ide> $query->distinct(false);
<ide> }
<add>
<ide> return $query;
<ide> }
<ide>
<ide> protected function _deleteQueryTranslator($query)
<ide>
<ide> list(, $field) = explode('.', $field);
<ide> $condition->setField($field);
<add>
<ide> return $condition;
<ide> });
<ide> }
<ide><path>src/Database/SqlserverCompiler.php
<ide> protected function _buildInsertPart($parts, $query, $generator)
<ide> {
<ide> $table = $parts[0];
<ide> $columns = $this->_stringifyExpressions($parts[1], $generator);
<add>
<ide> return sprintf('INSERT INTO %s (%s) OUTPUT INSERTED.*', $table, implode(', ', $columns));
<ide> }
<ide>
<ide><path>src/Database/Statement/BufferResultsTrait.php
<ide> trait BufferResultsTrait
<ide> public function bufferResults($buffer)
<ide> {
<ide> $this->_bufferResults = (bool)$buffer;
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Database/Statement/BufferedStatement.php
<ide> public function __construct($statement = null, $driver = null)
<ide> public function execute($params = null)
<ide> {
<ide> $this->_reset();
<add>
<ide> return parent::execute($params);
<ide> }
<ide>
<ide> public function fetch($type = 'num')
<ide> if ($this->_allFetched) {
<ide> $row = ($this->_counter < $this->_count) ? $this->_records[$this->_counter++] : false;
<ide> $row = ($row && $type === 'num') ? array_values($row) : $row;
<add>
<ide> return $row;
<ide> }
<ide>
<ide> public function fetch($type = 'num')
<ide> $this->_allFetched = true;
<ide> $this->_counter = $this->_count + 1;
<ide> $this->_statement->closeCursor();
<add>
<ide> return false;
<ide> }
<ide>
<ide> $this->_count++;
<add>
<ide> return $this->_records[] = $record;
<ide> }
<ide>
<ide> public function fetchAll($type = 'num')
<ide> $this->_count = count($this->_records);
<ide> $this->_allFetched = true;
<ide> $this->_statement->closeCursor();
<add>
<ide> return $this->_records;
<ide> }
<ide>
<ide><path>src/Database/Statement/CallbackStatement.php
<ide> public function fetch($type = 'num')
<ide> {
<ide> $callback = $this->_callback;
<ide> $row = $this->_statement->fetch($type);
<add>
<ide> return $row === false ? $row : $callback($row);
<ide> }
<ide>
<ide><path>src/Database/Statement/MysqlStatement.php
<ide> public function execute($params = null)
<ide> $this->_driver->connection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $this->_bufferResults);
<ide> $result = $this->_statement->execute($params);
<ide> $this->_driver->connection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>src/Database/Statement/PDOStatement.php
<ide> public function fetch($type = 'num')
<ide> if ($type === 'obj') {
<ide> return $this->_statement->fetch(PDO::FETCH_OBJ);
<ide> }
<add>
<ide> return $this->_statement->fetch($type);
<ide> }
<ide>
<ide> public function fetchAll($type = 'num')
<ide> if ($type === 'obj') {
<ide> return $this->_statement->fetchAll(PDO::FETCH_OBJ);
<ide> }
<add>
<ide> return $this->_statement->fetchAll($type);
<ide> }
<ide> }
<ide><path>src/Database/Statement/SqliteStatement.php
<ide> public function rowCount()
<ide> $changes->execute();
<ide> $count = $changes->fetch()[0];
<ide> $changes->closeCursor();
<add>
<ide> return (int)$count;
<ide> }
<add>
<ide> return parent::rowCount();
<ide> }
<ide> }
<ide><path>src/Database/Statement/StatementDecorator.php
<ide> public function errorInfo()
<ide> public function execute($params = null)
<ide> {
<ide> $this->_hasExecuted = true;
<add>
<ide> return $this->_statement->execute($params);
<ide> }
<ide>
<ide> public function getIterator()
<ide> if (!$this->_hasExecuted) {
<ide> $this->execute();
<ide> }
<add>
<ide> return $this->_statement;
<ide> }
<ide>
<ide> public function lastInsertId($table = null, $column = null)
<ide> if (isset($row[$column])) {
<ide> return $row[$column];
<ide> }
<add>
<ide> return $this->_driver->lastInsertId($table, $column);
<ide> }
<ide>
<ide><path>src/Database/Type.php
<ide> public static function buildAll()
<ide> foreach (self::$_types as $name => $type) {
<ide> $result[$name] = isset(static::$_builtTypes[$name]) ? static::$_builtTypes[$name] : static::build($name);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public static function map($type = null, $className = null)
<ide> }
<ide> if (is_array($type)) {
<ide> self::$_types = $type;
<add>
<ide> return null;
<ide> }
<ide> if ($className === null) {
<ide> protected function _basicTypeCast($value)
<ide> return $typeInfo['callback']($value);
<ide> }
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> public static function boolval($value)
<ide> if (is_string($value) && !is_numeric($value)) {
<ide> return strtolower($value) === 'true' ? true : false;
<ide> }
<add>
<ide> return !empty($value);
<ide> }
<ide>
<ide> public static function strval($value)
<ide> if (is_array($value)) {
<ide> $value = '';
<ide> }
<add>
<ide> return strval($value);
<ide> }
<ide>
<ide><path>src/Database/Type/BoolType.php
<ide> public function toPHP($value, Driver $driver)
<ide> if (is_string($value) && !is_numeric($value)) {
<ide> return strtolower($value) === 'true' ? true : false;
<ide> }
<add>
<ide> return !empty($value);
<ide> }
<ide>
<ide> public function marshal($value)
<ide> if ($value === 'false') {
<ide> return false;
<ide> }
<add>
<ide> return !empty($value);
<ide> }
<ide> }
<ide><path>src/Database/Type/DateTimeType.php
<ide> public function toDatabase($value, Driver $driver)
<ide> $class = $this->_className;
<ide> $value = new $class('@' . $value);
<ide> }
<add>
<ide> return $value->format($this->_format);
<ide> }
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> }
<ide>
<ide> $instance = clone $this->_datetimeInstance;
<add>
<ide> return $instance->modify($value);
<ide> }
<ide>
<ide> public function useLocaleParser($enable = true)
<ide> {
<ide> if ($enable === false) {
<ide> $this->_useLocaleParser = $enable;
<add>
<ide> return $this;
<ide> }
<ide> if (method_exists($this->_className, 'parseDateTime')) {
<ide> $this->_useLocaleParser = $enable;
<add>
<ide> return $this;
<ide> }
<ide> throw new RuntimeException(
<ide> public function useLocaleParser($enable = true)
<ide> public function setLocaleFormat($format)
<ide> {
<ide> $this->_localeFormat = $format;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function setLocaleFormat($format)
<ide> public function useImmutable()
<ide> {
<ide> $this->_setClassName('Cake\I18n\FrozenTime', 'DateTimeImmutable');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _setClassName($class, $fallback)
<ide> public function useMutable()
<ide> {
<ide> $this->_setClassName('Cake\I18n\Time', 'DateTime');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function useMutable()
<ide> protected function _parseValue($value)
<ide> {
<ide> $class = $this->_className;
<add>
<ide> return $class::parseDateTime($value, $this->_localeFormat);
<ide> }
<ide> }
<ide><path>src/Database/Type/DateType.php
<ide> class DateType extends DateTimeType
<ide> public function useImmutable()
<ide> {
<ide> $this->_setClassName('Cake\I18n\FrozenDate', 'DateTimeImmutable');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function useImmutable()
<ide> public function useMutable()
<ide> {
<ide> $this->_setClassName('Cake\I18n\Date', 'DateTime');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function marshal($value)
<ide> if ($date instanceof DateTime) {
<ide> $date->setTime(0, 0, 0);
<ide> }
<add>
<ide> return $date;
<ide> }
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> if ($date instanceof DateTime) {
<ide> $date->setTime(0, 0, 0);
<ide> }
<add>
<ide> return $date;
<ide> }
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> protected function _parseValue($value)
<ide> {
<ide> $class = $this->_className;
<add>
<ide> return $class::parseDate($value, $this->_localeFormat);
<ide> }
<ide> }
<ide><path>src/Database/Type/FloatType.php
<ide> public function toDatabase($value, Driver $driver)
<ide> if (is_array($value)) {
<ide> return 1;
<ide> }
<add>
<ide> return floatval($value);
<ide> }
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> if (is_array($value)) {
<ide> return 1;
<ide> }
<add>
<ide> return floatval($value);
<ide> }
<ide>
<ide> public function useLocaleParser($enable = true)
<ide> {
<ide> if ($enable === false) {
<ide> $this->_useLocaleParser = $enable;
<add>
<ide> return $this;
<ide> }
<ide> if (static::$numberClass === 'Cake\I18n\Number' ||
<ide> is_subclass_of(static::$numberClass, 'Cake\I18n\Number')
<ide> ) {
<ide> $this->_useLocaleParser = $enable;
<add>
<ide> return $this;
<ide> }
<ide> throw new RuntimeException(
<ide> public function useLocaleParser($enable = true)
<ide> protected function _parseValue($value)
<ide> {
<ide> $class = static::$numberClass;
<add>
<ide> return $class::parseFloat($value);
<ide> }
<ide> }
<ide><path>src/Database/Type/IntegerType.php
<ide> public function toPHP($value, Driver $driver)
<ide> if ($value === null) {
<ide> return null;
<ide> }
<add>
<ide> return (int)$value;
<ide> }
<ide>
<ide> public function marshal($value)
<ide> if (is_array($value)) {
<ide> return 1;
<ide> }
<add>
<ide> return null;
<ide> }
<ide> }
<ide><path>src/Database/Type/StringType.php
<ide> public function toPHP($value, Driver $driver)
<ide> if ($value === null) {
<ide> return null;
<ide> }
<add>
<ide> return (string)$value;
<ide> }
<ide>
<ide> public function marshal($value)
<ide> if (is_array($value)) {
<ide> return '';
<ide> }
<add>
<ide> return (string)$value;
<ide> }
<ide>
<ide><path>src/Database/Type/TimeType.php
<ide> class TimeType extends DateTimeType
<ide> protected function _parseValue($value)
<ide> {
<ide> $class = $this->_className;
<add>
<ide> return $class::parseTime($value, $this->_localeFormat);
<ide> }
<ide> }
<ide><path>src/Database/Type/UuidType.php
<ide> public function marshal($value)
<ide> if ($value === null || $value === '' || is_array($value)) {
<ide> return null;
<ide> }
<add>
<ide> return (string)$value;
<ide> }
<ide> }
<ide><path>src/Database/TypeConverterTrait.php
<ide> public function cast($value, $type)
<ide> $value = $type->toDatabase($value, $this->_driver);
<ide> $type = $type->toStatement($value, $this->_driver);
<ide> }
<add>
<ide> return [$value, $type];
<ide> }
<ide>
<ide> public function matchTypes($columns, $types)
<ide> $types = array_intersect_key($types, $positions);
<ide> $types = array_combine($positions, $types);
<ide> }
<add>
<ide> return $types;
<ide> }
<ide> }
<ide><path>src/Database/TypeMap.php
<ide> public function defaults(array $defaults = null)
<ide> return $this->_defaults;
<ide> }
<ide> $this->_defaults = $defaults;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function types(array $types = null)
<ide> return $this->_types;
<ide> }
<ide> $this->_types = $types;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function type($column)
<ide> if (isset($this->_defaults[$column])) {
<ide> return $this->_defaults[$column];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>src/Database/TypeMapTrait.php
<ide> public function typeMap($typeMap = null)
<ide> return $this->_typeMap;
<ide> }
<ide> $this->_typeMap = is_array($typeMap) ? new TypeMap($typeMap) : $typeMap;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function defaultTypes(array $types = null)
<ide> return $this->typeMap()->defaults();
<ide> }
<ide> $this->typeMap()->defaults($types);
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Database/TypedResultTrait.php
<ide> public function returnType($type = null)
<ide> {
<ide> if ($type !== null) {
<ide> $this->_returnType = $type;
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/Database/ValueBinder.php
<ide> public function placeholder($token)
<ide> if ($token[0] !== ':' || $token !== '?') {
<ide> $token = sprintf(':c%s', $number);
<ide> }
<add>
<ide> return $token;
<ide> }
<ide>
<ide><path>src/Datasource/ConnectionManager.php
<ide> public static function config($key, $config = null)
<ide> if (is_array($config)) {
<ide> $config['name'] = $key;
<ide> }
<add>
<ide> return static::_config($key, $config);
<ide> }
<ide>
<ide> public static function parseDsn($config = null)
<ide> }
<ide>
<ide> unset($config['path']);
<add>
<ide> return $config;
<ide> }
<ide>
<ide> public static function get($name, $useAliases = true)
<ide> if (isset(static::$_registry->{$name})) {
<ide> return static::$_registry->{$name};
<ide> }
<add>
<ide> return static::$_registry->load($name, static::$_config[$name]);
<ide> }
<ide> }
<ide><path>src/Datasource/ConnectionRegistry.php
<ide> protected function _resolveClassName($class)
<ide> if (is_object($class)) {
<ide> return $class;
<ide> }
<add>
<ide> return App::className($class, 'Datasource');
<ide> }
<ide>
<ide> protected function _create($class, $alias, $settings)
<ide> }
<ide>
<ide> unset($settings['className']);
<add>
<ide> return new $class($settings);
<ide> }
<ide>
<ide><path>src/Datasource/EntityTrait.php
<ide> public function &get($property)
<ide>
<ide> if ($method) {
<ide> $result = $this->{$method}($value);
<add>
<ide> return $result;
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> public function getOriginal($property)
<ide> if (array_key_exists($property, $this->_original)) {
<ide> return $this->_original[$property];
<ide> }
<add>
<ide> return $this->get($property);
<ide> }
<ide>
<ide> public function getOriginalValues()
<ide> $originals[$key] = $value;
<ide> }
<ide> }
<add>
<ide> return $originals;
<ide> }
<ide>
<ide> public function has($property)
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function hiddenProperties($properties = null)
<ide> return $this->_hidden;
<ide> }
<ide> $this->_hidden = $properties;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function virtualProperties($properties = null)
<ide> return $this->_virtual;
<ide> }
<ide> $this->_virtual = $properties;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function visibleProperties()
<ide> {
<ide> $properties = array_keys($this->_properties);
<ide> $properties = array_merge($properties, $this->_virtual);
<add>
<ide> return array_diff($properties, $this->_hidden);
<ide> }
<ide>
<ide> public function toArray()
<ide> $result[$property] = $value;
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function extract(array $properties, $onlyDirty = false)
<ide> $result[$property] = $this->get($property);
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function extractOriginal(array $properties)
<ide> foreach ($properties as $property) {
<ide> $result[$property] = $this->getOriginal($property);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function extractOriginalChanged(array $properties)
<ide> $result[$property] = $original;
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function dirty($property = null, $isDirty = null)
<ide>
<ide> if ($isDirty === false) {
<ide> unset($this->_dirty[$property]);
<add>
<ide> return false;
<ide> }
<ide>
<ide> $this->_dirty[$property] = true;
<ide> unset($this->_errors[$property], $this->_invalid[$property]);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function errors($field = null, $errors = null, $overwrite = false)
<ide> {
<ide> if ($field === null) {
<ide> $diff = array_diff_key($this->_properties, $this->_errors);
<add>
<ide> return $this->_errors + (new Collection($diff))
<ide> ->filter(function ($value) {
<ide> return is_array($value) || $value instanceof EntityInterface;
<ide> public function errors($field = null, $errors = null, $overwrite = false)
<ide> if ($errors) {
<ide> return $errors;
<ide> }
<add>
<ide> return $this->_nestedErrors($field);
<ide> }
<ide>
<ide> protected function _nestedErrors($field)
<ide> if (count($path) <= 1) {
<ide> return $this->_readError($entity, array_pop($path));
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> protected function _readError($object, $path = null)
<ide> return $val->errors();
<ide> }
<ide> }, $object);
<add>
<ide> return array_filter($array);
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> public function invalid($field = null, $value = null, $overwrite = false)
<ide>
<ide> if (is_string($field) && $value === null) {
<ide> $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null;
<add>
<ide> return $value;
<ide> }
<ide>
<ide> public function accessible($property, $set = null)
<ide> return (bool)$set;
<ide> }, $this->_accessible);
<ide> $this->_accessible['*'] = (bool)$set;
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/Datasource/ModelAwareTrait.php
<ide> public function loadModel($modelClass = null, $modelType = null)
<ide> if (!$this->{$alias}) {
<ide> throw new MissingModelException([$modelClass, $modelType]);
<ide> }
<add>
<ide> return $this->{$alias};
<ide> }
<ide>
<ide><path>src/Datasource/QueryCacher.php
<ide> public function fetch($query)
<ide> if (empty($result)) {
<ide> return null;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function store($query, Traversable $results)
<ide> {
<ide> $key = $this->_resolveKey($query);
<ide> $storage = $this->_resolveCacher();
<add>
<ide> return $storage->write($key, $results);
<ide> }
<ide>
<ide> protected function _resolveKey($query)
<ide> $msg = sprintf('Cache key functions must return a string. Got %s.', var_export($key, true));
<ide> throw new RuntimeException($msg);
<ide> }
<add>
<ide> return $key;
<ide> }
<ide>
<ide> protected function _resolveCacher()
<ide> if (is_string($this->_config)) {
<ide> return Cache::engine($this->_config);
<ide> }
<add>
<ide> return $this->_config;
<ide> }
<ide> }
<ide><path>src/Datasource/QueryTrait.php
<ide> public function repository(RepositoryInterface $table = null)
<ide> return $this->_repository;
<ide> }
<ide> $this->_repository = $table;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function repository(RepositoryInterface $table = null)
<ide> public function setResult($results)
<ide> {
<ide> $this->_results = $results;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function cache($key, $config = 'default')
<ide> {
<ide> if ($key === false) {
<ide> $this->_cache = null;
<add>
<ide> return $this;
<ide> }
<ide> $this->_cache = new QueryCacher($key, $config);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function eagerLoaded($value = null)
<ide> return $this->_eagerLoaded;
<ide> }
<ide> $this->_eagerLoaded = $value;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function all()
<ide> }
<ide> }
<ide> $this->_results = $results;
<add>
<ide> return $this->_results;
<ide> }
<ide>
<ide> public function mapReduce(callable $mapper = null, callable $reducer = null, $ov
<ide> return $this->_mapReduce;
<ide> }
<ide> $this->_mapReduce[] = compact('mapper', 'reducer');
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function formatResults(callable $formatter = null, $mode = 0)
<ide>
<ide> if ($mode === self::PREPEND) {
<ide> array_unshift($this->_formatters, $formatter);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> $this->_formatters[] = $formatter;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function first()
<ide> if ($this->_dirty) {
<ide> $this->limit(1);
<ide> }
<add>
<ide> return $this->all()->first();
<ide> }
<ide>
<ide> public function __call($method, $arguments)
<ide> $resultSetClass = $this->_decoratorClass();
<ide> if (in_array($method, get_class_methods($resultSetClass))) {
<ide> $results = $this->all();
<add>
<ide> return call_user_func_array([$results, $method], $arguments);
<ide> }
<ide> throw new BadMethodCallException(
<ide><path>src/Datasource/RuleInvoker.php
<ide> public function __construct(callable $rule, $name, array $options = [])
<ide> public function setOptions(array $options)
<ide> {
<ide> $this->options = $options + $this->options;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function setName($name)
<ide> if ($name) {
<ide> $this->name = $name;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/Datasource/RulesAwareTrait.php
<ide> public function checkRules(EntityInterface $entity, $operation = RulesChecker::C
<ide> return $event->result;
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function rulesChecker()
<ide> $class = defined('static::RULES_CLASS') ? static::RULES_CLASS : 'Cake\Datasource\RulesChecker';
<ide> $this->_rulesChecker = $this->buildRules(new $class(['repository' => $this]));
<ide> $this->dispatchEvent('Model.buildRules', ['rules' => $this->_rulesChecker]);
<add>
<ide> return $this->_rulesChecker;
<ide> }
<ide>
<ide><path>src/Datasource/RulesChecker.php
<ide> public function __construct(array $options = [])
<ide> public function add(callable $rule, $name = null, array $options = [])
<ide> {
<ide> $this->_rules[] = $this->_addError($rule, $name, $options);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function add(callable $rule, $name = null, array $options = [])
<ide> public function addCreate(callable $rule, $name = null, array $options = [])
<ide> {
<ide> $this->_createRules[] = $this->_addError($rule, $name, $options);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addCreate(callable $rule, $name = null, array $options = [])
<ide> public function addUpdate(callable $rule, $name = null, array $options = [])
<ide> {
<ide> $this->_updateRules[] = $this->_addError($rule, $name, $options);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addUpdate(callable $rule, $name = null, array $options = [])
<ide> public function addDelete(callable $rule, $name = null, array $options = [])
<ide> {
<ide> $this->_deleteRules[] = $this->_addError($rule, $name, $options);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _checkRules(EntityInterface $entity, array $options = [], arr
<ide> foreach ($rules as $rule) {
<ide> $success = $rule($entity, $options) && $success;
<ide> }
<add>
<ide> return $success;
<ide> }
<ide>
<ide> protected function _addError($rule, $name, $options)
<ide> } else {
<ide> $rule->setOptions($options)->setName($name);
<ide> }
<add>
<ide> return $rule;
<ide> }
<ide> }
<ide><path>src/Error/BaseErrorHandler.php
<ide> public function handleError($code, $description, $file = null, $line = null, $co
<ide> }
<ide> $this->_displayError($data, $debug);
<ide> $this->_logError($log, $data);
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function handleFatalError($code, $description, $file, $line)
<ide> $this->_logError(LOG_ERR, $data);
<ide>
<ide> $this->handleException(new FatalErrorException($description, 500, $file, $line));
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _logError($level, $data)
<ide> $message .= "\nTrace:\n" . $trace . "\n";
<ide> }
<ide> $message .= "\n\n";
<add>
<ide> return Log::write($level, $message);
<ide> }
<ide>
<ide> protected function _logException(Exception $exception)
<ide> }
<ide> }
<ide> }
<add>
<ide> return Log::error($this->_getMessage($exception));
<ide> }
<ide>
<ide> protected function _requestContext($request)
<ide> if ($clientIp && $clientIp !== '::1') {
<ide> $message .= "\nClient IP: " . $clientIp;
<ide> }
<add>
<ide> return $message;
<ide> }
<ide>
<ide> protected function _getMessage(Exception $exception)
<ide> if (!empty($config['trace'])) {
<ide> $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n";
<ide> }
<add>
<ide> return $message;
<ide> }
<ide>
<ide> public static function mapErrorCode($code)
<ide>
<ide> $error = $levelMap[$code];
<ide> $log = $logMap[$error];
<add>
<ide> return [ucfirst($error), $log];
<ide> }
<ide> }
<ide><path>src/Error/Debugger.php
<ide> public static function getInstance($class = null)
<ide> if (!$instance) {
<ide> $instance[0] = new Debugger();
<ide> }
<add>
<ide> return $instance[0];
<ide> }
<ide>
<ide> public static function formatTrace($backtrace, $options = [])
<ide> if ($options['format'] === 'array' || $options['format'] === 'points') {
<ide> return $back;
<ide> }
<add>
<ide> return implode("\n", $back);
<ide> }
<ide>
<ide> public static function excerpt($file, $line, $context = 2)
<ide> $lines[] = $string;
<ide> }
<ide> }
<add>
<ide> return $lines;
<ide> }
<ide>
<ide> protected static function _highlight($str)
<ide> $highlight
<ide> );
<ide> }
<add>
<ide> return $highlight;
<ide> }
<ide>
<ide> protected static function _export($var, $depth, $indent)
<ide> if (trim($var) === '') {
<ide> return "''";
<ide> }
<add>
<ide> return "'" . $var . "'";
<ide> case 'array':
<ide> return static::_array($var, $depth - 1, $indent + 1);
<ide> protected static function _array(array $var, $depth, $indent)
<ide> } else {
<ide> $vars[] = $break . '[maximum depth reached]';
<ide> }
<add>
<ide> return $out . implode(',', $vars) . $end . ']';
<ide> }
<ide>
<ide> protected static function _object($var, $depth, $indent)
<ide> $end . '}';
<ide> } catch (Exception $e) {
<ide> $message = $e->getMessage();
<add>
<ide> return $out . "\n(unable to export object: $message)\n }";
<ide> }
<ide> }
<ide> protected static function _object($var, $depth, $indent)
<ide> $out .= $break . implode($break, $props) . $end;
<ide> }
<ide> $out .= '}';
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public static function addFormat($format, array $strings)
<ide> } else {
<ide> $self->_templates[$format] = $strings;
<ide> }
<add>
<ide> return $self->_templates[$format];
<ide> }
<ide>
<ide> public function outputError($data)
<ide> switch ($this->_outputFormat) {
<ide> case false:
<ide> $this->_data[] = compact('context', 'trace') + $data;
<add>
<ide> return;
<ide> case 'log':
<ide> $this->log(compact('context', 'trace') + $data);
<add>
<ide> return;
<ide> }
<ide>
<ide> public static function getType($var)
<ide> if (is_resource($var)) {
<ide> return 'resource';
<ide> }
<add>
<ide> return 'unknown';
<ide> }
<ide>
<ide><path>src/Error/ErrorHandler.php
<ide> protected function _sendResponse($response)
<ide> {
<ide> if (is_string($response)) {
<ide> echo $response;
<add>
<ide> return;
<ide> }
<ide> $response->send();
<ide><path>src/Error/ExceptionRenderer.php
<ide> protected function _getController()
<ide> if (empty($controller)) {
<ide> $controller = new Controller($request, $response);
<ide> }
<add>
<ide> return $controller;
<ide> }
<ide>
<ide> public function render()
<ide> if ($unwrapped instanceof CakeException && $isDebug) {
<ide> $this->controller->set($unwrapped->getAttributes());
<ide> }
<add>
<ide> return $this->_outputMessage($template);
<ide> }
<ide>
<ide> protected function _customMethod($method, $exception)
<ide> $this->controller->response->body($result);
<ide> $result = $this->controller->response;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide> /**
<ide> protected function _method(Exception $exception)
<ide> }
<ide>
<ide> $method = Inflector::variable($baseClass) ?: 'error500';
<add>
<ide> return $this->method = $method;
<ide> }
<ide>
<ide> protected function _template(Exception $exception, $method, $code)
<ide> if ($code < 500) {
<ide> $template = 'error400';
<ide> }
<add>
<ide> return $this->template = $template;
<ide> }
<ide>
<ide> protected function _template(Exception $exception, $method, $code)
<ide> if ($code < 500) {
<ide> $template = 'error400';
<ide> }
<add>
<ide> return $this->template = $template;
<ide> }
<ide>
<ide> protected function _code(Exception $exception)
<ide> if ($errorCode >= 400 && $errorCode < 506) {
<ide> $code = $errorCode;
<ide> }
<add>
<ide> return $code;
<ide> }
<ide>
<ide> protected function _outputMessage($template)
<ide> {
<ide> try {
<ide> $this->controller->render($template);
<add>
<ide> return $this->_shutdown();
<ide> } catch (MissingTemplateException $e) {
<ide> $attributes = $e->getAttributes();
<ide> if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
<ide> return $this->_outputMessageSafe('error500');
<ide> }
<add>
<ide> return $this->_outputMessage('error500');
<ide> } catch (MissingPluginException $e) {
<ide> $attributes = $e->getAttributes();
<ide> if (isset($attributes['plugin']) && $attributes['plugin'] === $this->controller->plugin) {
<ide> $this->controller->plugin = null;
<ide> }
<add>
<ide> return $this->_outputMessageSafe('error500');
<ide> } catch (Exception $e) {
<ide> return $this->_outputMessageSafe('error500');
<ide> protected function _outputMessageSafe($template)
<ide>
<ide> $this->controller->response->body($view->render($template, 'error'));
<ide> $this->controller->response->type('html');
<add>
<ide> return $this->controller->response;
<ide> }
<ide>
<ide> protected function _shutdown()
<ide> 'response' => $this->controller->response
<ide> ];
<ide> $result = $dispatcher->dispatchEvent('Dispatcher.afterDispatch', $args);
<add>
<ide> return $result->data['response'];
<ide> }
<ide> }
<ide><path>src/Event/EventDispatcherTrait.php
<ide> public function eventManager(EventManager $eventManager = null)
<ide> } elseif (empty($this->_eventManager)) {
<ide> $this->_eventManager = new EventManager();
<ide> }
<add>
<ide> return $this->_eventManager;
<ide> }
<ide>
<ide><path>src/Event/EventList.php
<ide> public function offsetGet($offset)
<ide> if ($this->offsetExists($offset)) {
<ide> return $this->_events[$offset];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function hasEvent($name)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide> }
<ide><path>src/Event/EventManager.php
<ide> public static function instance($manager = null)
<ide> }
<ide>
<ide> static::$_generalManager->_isGlobal = true;
<add>
<ide> return static::$_generalManager;
<ide> }
<ide>
<ide> public function attach($callable, $eventKey = null, array $options = [])
<ide> {
<ide> if ($eventKey === null) {
<ide> $this->on($callable);
<add>
<ide> return;
<ide> }
<ide> if ($options) {
<ide> $this->on($eventKey, $options, $callable);
<add>
<ide> return;
<ide> }
<ide> $this->on($eventKey, $callable);
<ide> public function on($eventKey = null, $options = [], $callable = null)
<ide> {
<ide> if ($eventKey instanceof EventListenerInterface) {
<ide> $this->_attachSubscriber($eventKey);
<add>
<ide> return;
<ide> }
<ide> $argCount = func_num_args();
<ide> if ($argCount === 2) {
<ide> $this->_listeners[$eventKey][static::$defaultPriority][] = [
<ide> 'callable' => $options
<ide> ];
<add>
<ide> return;
<ide> }
<ide> if ($argCount === 3) {
<ide> $priority = isset($options['priority']) ? $options['priority'] : static::$defaultPriority;
<ide> $this->_listeners[$eventKey][$priority][] = [
<ide> 'callable' => $callable
<ide> ];
<add>
<ide> return;
<ide> }
<ide> throw new InvalidArgumentException('Invalid arguments for EventManager::on().');
<ide> protected function _extractCallable($function, $object)
<ide> if (is_string($method)) {
<ide> $method = [$object, $method];
<ide> }
<add>
<ide> return [$method, $options];
<ide> }
<ide>
<ide> public function detach($callable, $eventKey = null)
<ide> {
<ide> if ($eventKey === null) {
<ide> $this->off($callable);
<add>
<ide> return;
<ide> }
<ide> $this->off($eventKey, $callable);
<ide> public function off($eventKey, $callable = null)
<ide> {
<ide> if ($eventKey instanceof EventListenerInterface) {
<ide> $this->_detachSubscriber($eventKey);
<add>
<ide> return;
<ide> }
<ide> if ($callable instanceof EventListenerInterface) {
<ide> $this->_detachSubscriber($callable, $eventKey);
<add>
<ide> return;
<ide> }
<ide> if ($callable === null && is_string($eventKey)) {
<ide> unset($this->_listeners[$eventKey]);
<add>
<ide> return;
<ide> }
<ide> if ($callable === null) {
<ide> foreach (array_keys($this->_listeners) as $name) {
<ide> $this->off($name, $eventKey);
<ide> }
<add>
<ide> return;
<ide> }
<ide> if (empty($this->_listeners[$eventKey])) {
<ide> public function dispatch($event)
<ide> if ($this->_trackEvents) {
<ide> $this->addEventToList($event);
<ide> }
<add>
<ide> return $event;
<ide> }
<ide>
<ide> public function dispatch($event)
<ide> if ($this->_trackEvents) {
<ide> $this->addEventToList($event);
<ide> }
<add>
<ide> return $event;
<ide> }
<ide>
<ide> protected function _callListener(callable $listener, Event $event)
<ide> return $listener($event, $data[0], $data[1], $data[2]);
<ide> default:
<ide> array_unshift($data, $event);
<add>
<ide> return call_user_func_array($listener, $data);
<ide> }
<ide> }
<ide> public function listeners($eventKey)
<ide> $result = array_merge($result, $localListeners[$priority]);
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function prioritisedListeners($eventKey)
<ide> if (empty($this->_listeners[$eventKey])) {
<ide> return [];
<ide> }
<add>
<ide> return $this->_listeners[$eventKey];
<ide> }
<ide>
<ide> public function matchingListeners($eventKeyPattern)
<ide> preg_grep($matchPattern, array_keys($this->_listeners), 0)
<ide> )
<ide> );
<add>
<ide> return $matches;
<ide> }
<ide>
<ide> public function __debugInfo()
<ide> $properties['_dispatchedEvents'][] = $event->name() . ' with subject ' . get_class($event->subject());
<ide> }
<ide> }
<add>
<ide> return $properties;
<ide> }
<ide> }
<ide><path>src/Filesystem/File.php
<ide> public function create()
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function open($mode = 'r', $force = false)
<ide> }
<ide>
<ide> $this->handle = fopen($this->path, $mode);
<add>
<ide> return is_resource($this->handle);
<ide> }
<ide>
<ide> public function read($bytes = false, $mode = 'rb', $force = false)
<ide> if ($bytes === false) {
<ide> $this->close();
<ide> }
<add>
<ide> return trim($data);
<ide> }
<ide>
<ide> public function offset($offset = false, $seek = SEEK_SET)
<ide> } elseif ($this->open() === true) {
<ide> return fseek($this->handle, $offset, $seek) === 0;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function prepare($data, $forceWindows = false)
<ide> if (DIRECTORY_SEPARATOR === '\\' || $forceWindows === true) {
<ide> $lineBreak = "\r\n";
<ide> }
<add>
<ide> return strtr($data, ["\r\n" => $lineBreak, "\n" => $lineBreak, "\r" => $lineBreak]);
<ide> }
<ide>
<ide> public function write($data, $mode = 'w', $force = false)
<ide> flock($this->handle, LOCK_UN);
<ide> }
<ide> }
<add>
<ide> return $success;
<ide> }
<ide>
<ide> public function close()
<ide> if (!is_resource($this->handle)) {
<ide> return true;
<ide> }
<add>
<ide> return fclose($this->handle);
<ide> }
<ide>
<ide> public function delete()
<ide> if ($this->exists()) {
<ide> return unlink($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function info()
<ide> if (!isset($this->info['mime'])) {
<ide> $this->info['mime'] = $this->mime();
<ide> }
<add>
<ide> return $this->info;
<ide> }
<ide>
<ide> public function ext()
<ide> if (isset($this->info['extension'])) {
<ide> return $this->info['extension'];
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function name()
<ide> if ($this->name) {
<ide> return $this->name;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function safe($name = null, $ext = null)
<ide> if (!$ext) {
<ide> $ext = $this->ext();
<ide> }
<add>
<ide> return preg_replace("/(?:[^\w\.-]+)/", "_", basename($name, $ext));
<ide> }
<ide>
<ide> public function pwd()
<ide> $this->path = $this->Folder->slashTerm($dir) . $this->name;
<ide> }
<ide> }
<add>
<ide> return $this->path;
<ide> }
<ide>
<ide> public function pwd()
<ide> public function exists()
<ide> {
<ide> $this->clearStatCache();
<add>
<ide> return (file_exists($this->path) && is_file($this->path));
<ide> }
<ide>
<ide> public function perms()
<ide> if ($this->exists()) {
<ide> return substr(sprintf('%o', fileperms($this->path)), -4);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function size()
<ide> if ($this->exists()) {
<ide> return filesize($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function owner()
<ide> if ($this->exists()) {
<ide> return fileowner($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function group()
<ide> if ($this->exists()) {
<ide> return filegroup($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function lastAccess()
<ide> if ($this->exists()) {
<ide> return fileatime($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function lastChange()
<ide> if ($this->exists()) {
<ide> return filemtime($this->path);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function copy($dest, $overwrite = true)
<ide> if (!$this->exists() || is_file($dest) && !$overwrite) {
<ide> return false;
<ide> }
<add>
<ide> return copy($this->path, $dest);
<ide> }
<ide>
<ide> public function mime()
<ide> return false;
<ide> }
<ide> list($type) = explode(';', $type);
<add>
<ide> return $type;
<ide> }
<ide> if (function_exists('mime_content_type')) {
<ide> return mime_content_type($this->pwd());
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Filesystem/Folder.php
<ide> public function cd($path)
<ide> if (is_dir($path)) {
<ide> return $this->path = $path;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function read($sort = self::SORT_NAME, $exceptions = false, $fullPath = f
<ide> public function find($regexpPattern = '.*', $sort = false)
<ide> {
<ide> list(, $files) = $this->read($sort);
<add>
<ide> return array_values(preg_grep('/^' . $regexpPattern . '$/i', $files));
<ide> }
<ide>
<ide> public function findRecursive($pattern = '.*', $sort = false)
<ide> $startsOn = $this->path;
<ide> $out = $this->_findRecursive($pattern, $sort);
<ide> $this->cd($startsOn);
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _findRecursive($pattern, $sort = false)
<ide> $this->cd(Folder::addPathElement($start, $dir));
<ide> $found = array_merge($found, $this->findRecursive($pattern, $sort));
<ide> }
<add>
<ide> return $found;
<ide> }
<ide>
<ide> public static function isAbsolute($path)
<ide> if (empty($path)) {
<ide> return false;
<ide> }
<add>
<ide> return $path[0] === '/' ||
<ide> preg_match('/^[A-Z]:\\\\/i', $path) ||
<ide> substr($path, 0, 2) === '\\\\' ||
<ide> public static function slashTerm($path)
<ide> if (Folder::isSlashTerm($path)) {
<ide> return $path;
<ide> }
<add>
<ide> return $path . Folder::correctSlashFor($path);
<ide> }
<ide>
<ide> public static function addPathElement($path, $element)
<ide> {
<ide> $element = (array)$element;
<ide> array_unshift($element, rtrim($path, DIRECTORY_SEPARATOR));
<add>
<ide> return implode(DIRECTORY_SEPARATOR, $element);
<ide> }
<ide>
<ide> public function inPath($path = '', $reverse = false)
<ide> } else {
<ide> $return = preg_match('/^(.*)' . preg_quote($current, '/') . '(.*)/', $dir);
<ide> }
<add>
<ide> return (bool)$return;
<ide> }
<ide>
<ide> public function chmod($path, $mode = false, $recursive = true, array $exceptions
<ide> if (@chmod($path, intval($mode, 8))) {
<ide> //@codingStandardsIgnoreEnd
<ide> $this->_messages[] = sprintf('%s changed to %s', $path, $mode);
<add>
<ide> return true;
<ide> }
<ide>
<ide> $this->_errors[] = sprintf('%s NOT changed to %s', $path, $mode);
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function chmod($path, $mode = false, $recursive = true, array $exceptions
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function subdirectories($path = null, $fullPath = true)
<ide> }
<ide> $subdirectories[] = $fullPath ? $item->getRealPath() : $item->getFilename();
<ide> }
<add>
<ide> return $subdirectories;
<ide> }
<ide>
<ide> public function tree($path = null, $exceptions = false, $type = null)
<ide> if ($type === null) {
<ide> return [[], []];
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> public function tree($path = null, $exceptions = false, $type = null)
<ide> if ($type === 'dir') {
<ide> return $directories;
<ide> }
<add>
<ide> return $files;
<ide> }
<ide>
<ide> public function create($pathname, $mode = false)
<ide>
<ide> if (is_file($pathname)) {
<ide> $this->_errors[] = sprintf('%s is a file', $pathname);
<add>
<ide> return false;
<ide> }
<ide> $pathname = rtrim($pathname, DIRECTORY_SEPARATOR);
<ide> public function create($pathname, $mode = false)
<ide> if (mkdir($pathname, $mode, true)) {
<ide> umask($old);
<ide> $this->_messages[] = sprintf('%s created', $pathname);
<add>
<ide> return true;
<ide> }
<ide> umask($old);
<ide> $this->_errors[] = sprintf('%s NOT created', $pathname);
<add>
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function dirsize()
<ide> }
<ide> $j = count($stack);
<ide> }
<add>
<ide> return $size;
<ide> }
<ide>
<ide> public function delete($path = null)
<ide> $this->_messages[] = sprintf('%s removed', $filePath);
<ide> } else {
<ide> $this->_errors[] = sprintf('%s NOT removed', $filePath);
<add>
<ide> return false;
<ide> }
<ide> }
<ide> public function delete($path = null)
<ide> $this->_messages[] = sprintf('%s removed', $path);
<ide> } else {
<ide> $this->_errors[] = sprintf('%s NOT removed', $path);
<add>
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function copy($options)
<ide>
<ide> if (!$this->cd($fromDir)) {
<ide> $this->_errors[] = sprintf('%s not found', $fromDir);
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function copy($options)
<ide>
<ide> if (!is_writable($toDir)) {
<ide> $this->_errors[] = sprintf('%s not writable', $toDir);
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function move($options)
<ide> return (bool)$this->cd($options['to']);
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function messages($reset = true)
<ide> if ($reset) {
<ide> $this->_messages = [];
<ide> }
<add>
<ide> return $messages;
<ide> }
<ide>
<ide> public function errors($reset = true)
<ide> if ($reset) {
<ide> $this->_errors = [];
<ide> }
<add>
<ide> return $errors;
<ide> }
<ide>
<ide> public function realpath($path)
<ide> if (!Folder::isAbsolute($path)) {
<ide> $path = Folder::addPathElement($this->path, $path);
<ide> }
<add>
<ide> return $path;
<ide> }
<ide> $path = str_replace('/', DIRECTORY_SEPARATOR, trim($path));
<ide> public function realpath($path)
<ide> array_pop($newparts);
<ide> continue;
<ide> }
<add>
<ide> return false;
<ide> }
<ide> $newparts[] = $part;
<ide> public function realpath($path)
<ide> public static function isSlashTerm($path)
<ide> {
<ide> $lastChar = $path[strlen($path) - 1];
<add>
<ide> return $lastChar === '/' || $lastChar === '\\';
<ide> }
<ide> }
<ide><path>src/Form/Form.php
<ide> public function schema(Schema $schema = null)
<ide> if ($schema) {
<ide> $this->_schema = $schema;
<ide> }
<add>
<ide> return $this->_schema;
<ide> }
<ide>
<ide> public function validator(Validator $validator = null)
<ide> if ($validator) {
<ide> $this->_validator = $validator;
<ide> }
<add>
<ide> return $this->_validator;
<ide> }
<ide>
<ide> public function validate(array $data)
<ide> {
<ide> $validator = $this->validator();
<ide> $this->_errors = $validator->errors($data);
<add>
<ide> return count($this->_errors) === 0;
<ide> }
<ide>
<ide> public function execute(array $data)
<ide> if (!$this->validate($data)) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_execute($data);
<ide> }
<ide>
<ide> public function __debugInfo()
<ide> '_errors' => $this->errors(),
<ide> '_validator' => $this->validator()->__debugInfo()
<ide> ];
<add>
<ide> return $special + get_object_vars($this);
<ide> }
<ide> }
<ide><path>src/Form/Schema.php
<ide> public function addFields(array $fields)
<ide> foreach ($fields as $name => $attrs) {
<ide> $this->addField($name, $attrs);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addField($name, $attrs)
<ide> }
<ide> $attrs = array_intersect_key($attrs, $this->_fieldDefaults);
<ide> $this->_fields[$name] = $attrs + $this->_fieldDefaults;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addField($name, $attrs)
<ide> public function removeField($name)
<ide> {
<ide> unset($this->_fields[$name]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function field($name)
<ide> if (!isset($this->_fields[$name])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->_fields[$name];
<ide> }
<ide>
<ide> public function fieldType($name)
<ide> if (!$field) {
<ide> return null;
<ide> }
<add>
<ide> return $field['type'];
<ide> }
<ide>
<ide><path>src/I18n/ChainMessagesLoader.php
<ide> public function __invoke()
<ide> return $package;
<ide> }
<ide> }
<add>
<ide> return new Package;
<ide> }
<ide> }
<ide><path>src/I18n/DateFormatTrait.php
<ide> public function i18nFormat($format = null, $timezone = null, $locale = null)
<ide>
<ide> $format = $format !== null ? $format : static::$_toStringFormat;
<ide> $locale = $locale ?: static::$defaultLocale;
<add>
<ide> return $this->_formatObject($time, $format, $locale);
<ide> }
<ide>
<ide> public static function parseDateTime($time, $format = null)
<ide> $time = $formatter->parse($time);
<ide> if ($time !== false) {
<ide> $result = new static('@' . $time);
<add>
<ide> return static::$_isDateInstance ? $result : $result->setTimezone($defaultTimezone);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public static function parseDate($date, $format = null)
<ide> $format = [$format, -1];
<ide> }
<ide> $format = $format ?: static::$wordFormat;
<add>
<ide> return static::parseDateTime($date, $format);
<ide> }
<ide>
<ide> public static function parseTime($time, $format = null)
<ide> $format = [-1, $format];
<ide> }
<ide> $format = $format ?: [-1, IntlDateFormatter::SHORT];
<add>
<ide> return static::parseDateTime($time, $format);
<ide> }
<ide>
<ide> public static function diffFormatter($formatter = null)
<ide> if (static::$diffFormatter === null) {
<ide> static::$diffFormatter = new RelativeTimeFormatter();
<ide> }
<add>
<ide> return static::$diffFormatter;
<ide> }
<add>
<ide> return static::$diffFormatter = $formatter;
<ide> }
<ide>
<ide><path>src/I18n/FrozenTime.php
<ide> public static function listTimezones($filter = null, $country = null, $options =
<ide> $groupedIdentifiers[$item[0]] = [$tz => $item[0] . $abbr];
<ide> }
<ide> }
<add>
<ide> return $groupedIdentifiers;
<ide> }
<add>
<ide> return array_combine($identifiers, $identifiers);
<ide> }
<ide>
<ide> public function wasWithinLast($timeInterval)
<ide> if (is_numeric($tmp)) {
<ide> $timeInterval = $tmp . ' days';
<ide> }
<add>
<ide> return parent::wasWithinLast($timeInterval);
<ide> }
<ide>
<ide> public function isWithinNext($timeInterval)
<ide> if (is_numeric($tmp)) {
<ide> $timeInterval = $tmp . ' days';
<ide> }
<add>
<ide> return parent::isWithinNext($timeInterval);
<ide> }
<ide> }
<ide><path>src/I18n/I18n.php
<ide> public static function translators()
<ide> if (class_exists('Cake\Cache\Cache')) {
<ide> static::$_collection->setCacher(Cache::engine('_cake_core_'));
<ide> }
<add>
<ide> return static::$_collection;
<ide> }
<ide>
<ide> public static function translator($name = 'default', $locale = null, callable $l
<ide>
<ide> $packages = static::translators()->getPackages();
<ide> $packages->set($name, $locale, $loader);
<add>
<ide> return null;
<ide> }
<ide>
<ide> public static function locale($locale = null)
<ide> if (isset(static::$_collection)) {
<ide> static::translators()->setLocale($locale);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public static function defaultLocale()
<ide> if (static::$_defaultLocale === null) {
<ide> static::$_defaultLocale = Locale::getDefault() ?: static::DEFAULT_LOCALE;
<ide> }
<add>
<ide> return static::$_defaultLocale;
<ide> }
<ide>
<ide><path>src/I18n/MessagesFileLoader.php
<ide> public function __invoke()
<ide>
<ide> $messages = (new $class)->parse($file);
<ide> $package->setMessages($messages);
<add>
<ide> return $package;
<ide> }
<ide>
<ide><path>src/I18n/Number.php
<ide> class Number
<ide> public static function precision($value, $precision = 3, array $options = [])
<ide> {
<ide> $formatter = static::formatter(['precision' => $precision, 'places' => $precision] + $options);
<add>
<ide> return $formatter->format($value);
<ide> }
<ide>
<ide> public static function toPercentage($value, $precision = 2, array $options = [])
<ide> if ($options['multiply']) {
<ide> $value *= 100;
<ide> }
<add>
<ide> return static::precision($value, $precision, $options) . '%';
<ide> }
<ide>
<ide> public static function format($value, array $options = [])
<ide> {
<ide> $formatter = static::formatter($options);
<ide> $options += ['before' => '', 'after' => ''];
<add>
<ide> return $options['before'] . $formatter->format($value) . $options['after'];
<ide> }
<ide>
<ide> public static function format($value, array $options = [])
<ide> public static function parseFloat($value, array $options = [])
<ide> {
<ide> $formatter = static::formatter($options);
<add>
<ide> return (float)$formatter->parse($value, NumberFormatter::TYPE_DOUBLE);
<ide> }
<ide>
<ide> public static function formatDelta($value, array $options = [])
<ide> $value = number_format($value, $options['places'], '.', '');
<ide> $sign = $value > 0 ? '+' : '';
<ide> $options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
<add>
<ide> return static::format($value, $options);
<ide> }
<ide>
<ide> public static function currency($value, $currency = null, array $options = [])
<ide> if (!empty($options['fractionSymbol']) && $abs > 0 && $abs < 1) {
<ide> $value = $value * 100;
<ide> $pos = isset($options['fractionPosition']) ? $options['fractionPosition'] : 'after';
<add>
<ide> return static::format($value, ['precision' => 0, $pos => $options['fractionSymbol']]);
<ide> }
<ide>
<ide> $before = isset($options['before']) ? $options['before'] : null;
<ide> $after = isset($options['after']) ? $options['after'] : null;
<add>
<ide> return $before . $formatter->formatCurrency($value, $currency) . $after;
<ide> }
<ide>
<ide> public static function formatter($options = [])
<ide> }
<ide>
<ide> $formatter = clone $formatter;
<add>
<ide> return static::_setAttributes($formatter, $options);
<ide> }
<ide>
<ide><path>src/I18n/Parser/MoFileParser.php
<ide> public function parse($resource)
<ide> }
<ide>
<ide> fclose($stream);
<add>
<ide> return $messages;
<ide> }
<ide>
<ide><path>src/I18n/RelativeTimeFormatter.php
<ide> public function diffForHumans(ChronosInterface $date, ChronosInterface $other =
<ide> if ($isNow) {
<ide> return $isFuture ? __d('cake', '{0} from now', $message) : __d('cake', '{0} ago', $message);
<ide> }
<add>
<ide> return $isFuture ? __d('cake', '{0} after', $message) : __d('cake', '{0} before', $message);
<ide> }
<ide>
<ide> public function timeAgoInWords(DatetimeInterface $time, array $options = [])
<ide> 'month' => __d('cake', 'about a month ago'),
<ide> 'year' => __d('cake', 'about a year ago')
<ide> ];
<add>
<ide> return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord];
<ide> }
<ide>
<ide> public function timeAgoInWords(DatetimeInterface $time, array $options = [])
<ide> 'month' => __d('cake', 'in about a month'),
<ide> 'year' => __d('cake', 'in about a year')
<ide> ];
<add>
<ide> return $aboutIn[$fWord];
<ide> }
<ide>
<ide> protected function _diffData($futureTime, $pastTime, $backwards, $options)
<ide> }
<ide>
<ide> $fNum = str_replace(['year', 'month', 'week', 'day', 'hour', 'minute', 'second'], [1, 2, 3, 4, 5, 6, 7], $fWord);
<add>
<ide> return [$fNum, $fWord, $years, $months, $weeks, $days, $hours, $minutes, $seconds];
<ide> }
<ide>
<ide> public function dateAgoInWords(DatetimeInterface $date, array $options = [])
<ide> 'month' => __d('cake', 'about a month ago'),
<ide> 'year' => __d('cake', 'about a year ago')
<ide> ];
<add>
<ide> return $relativeDate ? sprintf($options['relativeString'], $relativeDate) : $aboutAgo[$fWord];
<ide> }
<ide>
<ide> public function dateAgoInWords(DatetimeInterface $date, array $options = [])
<ide> 'month' => __d('cake', 'in about a month'),
<ide> 'year' => __d('cake', 'in about a year')
<ide> ];
<add>
<ide> return $aboutIn[$fWord];
<ide> }
<ide>
<ide> protected function _options($options, $class)
<ide> } else {
<ide> $options['accuracy'] += $class::$wordAccuracy;
<ide> }
<add>
<ide> return $options;
<ide> }
<ide> }
<ide><path>src/I18n/Time.php
<ide> public static function listTimezones($filter = null, $country = null, $options =
<ide> $groupedIdentifiers[$item[0]] = [$tz => $item[0] . $abbr];
<ide> }
<ide> }
<add>
<ide> return $groupedIdentifiers;
<ide> }
<add>
<ide> return array_combine($identifiers, $identifiers);
<ide> }
<ide>
<ide> public function wasWithinLast($timeInterval)
<ide> if (is_numeric($tmp)) {
<ide> $timeInterval = $tmp . ' days';
<ide> }
<add>
<ide> return parent::wasWithinLast($timeInterval);
<ide> }
<ide>
<ide> public function isWithinNext($timeInterval)
<ide> if (is_numeric($tmp)) {
<ide> $timeInterval = $tmp . ' days';
<ide> }
<add>
<ide> return parent::isWithinNext($timeInterval);
<ide> }
<ide> }
<ide><path>src/I18n/TranslatorRegistry.php
<ide> protected function _getTranslator($name, $locale)
<ide> if (!isset($this->_loaders[$name])) {
<ide> $this->registerLoader($name, $this->_partialLoader());
<ide> }
<add>
<ide> return $this->_getFromLoader($name, $locale);
<ide> }
<ide>
<ide> public function defaultFormatter($name = null)
<ide> if ($name === null) {
<ide> return $this->_defaultFormatter;
<ide> }
<add>
<ide> return $this->_defaultFormatter = $name;
<ide> }
<ide>
<ide> protected function _fallbackLoader($name, $locale)
<ide> $chain = function () use ($formatter, $chain) {
<ide> $package = $chain();
<ide> $package->setFormatter($formatter);
<add>
<ide> return $package;
<ide> };
<ide>
<ide> protected function _getFromLoader($name, $locale)
<ide> $loader = $this->setLoaderFallback($name, $loader);
<ide>
<ide> $this->packages->set($name, $locale, $loader);
<add>
<ide> return parent::get($name, $locale);
<ide> }
<ide>
<ide> public function setLoaderFallback($name, callable $loader)
<ide> if (!$package->getFallback()) {
<ide> $package->setFallback($fallbackDomain);
<ide> }
<add>
<ide> return $package;
<ide> };
<ide>
<ide><path>src/I18n/functions.php
<ide> function __($singular, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 2 ? (array)$args : array_slice(func_get_args(), 1);
<add>
<ide> return I18n::translator()->translate($singular, $arguments);
<ide> }
<ide>
<ide> function __n($singular, $plural, $count, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 4 ? (array)$args : array_slice(func_get_args(), 3);
<add>
<ide> return I18n::translator()->translate(
<ide> $plural,
<ide> ['_count' => $count, '_singular' => $singular] + $arguments
<ide> function __d($domain, $msg, $args = null)
<ide> return null;
<ide> }
<ide> $arguments = func_num_args() === 3 ? (array)$args : array_slice(func_get_args(), 2);
<add>
<ide> return I18n::translator($domain)->translate($msg, $arguments);
<ide> }
<ide>
<ide> function __dn($domain, $singular, $plural, $count, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 5 ? (array)$args : array_slice(func_get_args(), 4);
<add>
<ide> return I18n::translator($domain)->translate(
<ide> $plural,
<ide> ['_count' => $count, '_singular' => $singular] + $arguments
<ide> function __x($context, $singular, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 3 ? (array)$args : array_slice(func_get_args(), 2);
<add>
<ide> return I18n::translator()->translate($singular, ['_context' => $context] + $arguments);
<ide> }
<ide>
<ide> function __xn($context, $singular, $plural, $count, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 5 ? (array)$args : array_slice(func_get_args(), 2);
<add>
<ide> return I18n::translator()->translate(
<ide> $plural,
<ide> ['_count' => $count, '_singular' => $singular, '_context' => $context] + $arguments
<ide> function __dx($domain, $context, $msg, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 4 ? (array)$args : array_slice(func_get_args(), 2);
<add>
<ide> return I18n::translator($domain)->translate(
<ide> $msg,
<ide> ['_context' => $context] + $arguments
<ide> function __dxn($domain, $context, $singular, $plural, $count, $args = null)
<ide> }
<ide>
<ide> $arguments = func_num_args() === 6 ? (array)$args : array_slice(func_get_args(), 2);
<add>
<ide> return I18n::translator($domain)->translate(
<ide> $plural,
<ide> ['_count' => $count, '_singular' => $singular, '_context' => $context] + $arguments
<ide><path>src/Log/Engine/ConsoleLog.php
<ide> public function log($level, $message, array $context = [])
<ide> {
<ide> $message = $this->_format($message, $context);
<ide> $output = date('Y-m-d H:i:s') . ' ' . ucfirst($level) . ': ' . $message;
<add>
<ide> return $this->_output->write(sprintf('<%s>%s</%s>', $level, $output, $level));
<ide> }
<ide> }
<ide><path>src/Mailer/AbstractTransport.php
<ide> protected function _headersToString($headers, $eol = "\r\n")
<ide> if (!empty($out)) {
<ide> $out = substr($out, 0, -1 * strlen($eol));
<ide> }
<add>
<ide> return $out;
<ide> }
<ide> }
<ide><path>src/Mailer/Email.php
<ide> public function from($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_from;
<ide> }
<add>
<ide> return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.');
<ide> }
<ide>
<ide> public function sender($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_sender;
<ide> }
<add>
<ide> return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.');
<ide> }
<ide>
<ide> public function replyTo($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_replyTo;
<ide> }
<add>
<ide> return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.');
<ide> }
<ide>
<ide> public function readReceipt($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_readReceipt;
<ide> }
<add>
<ide> return $this->_setEmailSingle('_readReceipt', $email, $name, 'Disposition-Notification-To requires only 1 email address.');
<ide> }
<ide>
<ide> public function returnPath($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_returnPath;
<ide> }
<add>
<ide> return $this->_setEmailSingle('_returnPath', $email, $name, 'Return-Path requires only 1 email address.');
<ide> }
<ide>
<ide> public function to($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_to;
<ide> }
<add>
<ide> return $this->_setEmail('_to', $email, $name);
<ide> }
<ide>
<ide> public function cc($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_cc;
<ide> }
<add>
<ide> return $this->_setEmail('_cc', $email, $name);
<ide> }
<ide>
<ide> public function bcc($email = null, $name = null)
<ide> if ($email === null) {
<ide> return $this->_bcc;
<ide> }
<add>
<ide> return $this->_setEmail('_bcc', $email, $name);
<ide> }
<ide>
<ide> public function charset($charset = null)
<ide> if (empty($this->headerCharset)) {
<ide> $this->headerCharset = $charset;
<ide> }
<add>
<ide> return $this->charset;
<ide> }
<ide>
<ide> public function headerCharset($charset = null)
<ide> if ($charset === null) {
<ide> return $this->headerCharset;
<ide> }
<add>
<ide> return $this->headerCharset = $charset;
<ide> }
<ide>
<ide> public function emailPattern($regex = false)
<ide> return $this->_emailPattern;
<ide> }
<ide> $this->_emailPattern = $regex;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _setEmail($varName, $email, $name)
<ide> $name = $email;
<ide> }
<ide> $this->{$varName} = [$email => $name];
<add>
<ide> return $this;
<ide> }
<ide> $list = [];
<ide> protected function _setEmail($varName, $email, $name)
<ide> $list[$key] = $value;
<ide> }
<ide> $this->{$varName} = $list;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage)
<ide> $this->{$varName} = $current;
<ide> throw new InvalidArgumentException($throwMessage);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _addEmail($varName, $email, $name)
<ide> $name = $email;
<ide> }
<ide> $this->{$varName}[$email] = $name;
<add>
<ide> return $this;
<ide> }
<ide> $list = [];
<ide> protected function _addEmail($varName, $email, $name)
<ide> $list[$key] = $value;
<ide> }
<ide> $this->{$varName} = array_merge($this->{$varName}, $list);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function subject($subject = null)
<ide> return $this->_subject;
<ide> }
<ide> $this->_subject = $this->_encode((string)$subject);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function subject($subject = null)
<ide> public function setHeaders(array $headers)
<ide> {
<ide> $this->_headers = $headers;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function setHeaders(array $headers)
<ide> public function addHeaders(array $headers)
<ide> {
<ide> $this->_headers = array_merge($this->_headers, $headers);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _formatAddress($address)
<ide> $return[] = sprintf('%s <%s>', $encoded, $email);
<ide> }
<ide> }
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public function template($template = false, $layout = false)
<ide> if ($layout !== false) {
<ide> $this->viewBuilder()->layout($layout ?: false);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function viewRender($viewClass = null)
<ide> return $this->viewBuilder()->className();
<ide> }
<ide> $this->viewBuilder()->className($viewClass);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function viewVars($viewVars = null)
<ide> return $this->viewVars;
<ide> }
<ide> $this->set((array)$viewVars);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function theme($theme = null)
<ide> return $this->viewBuilder()->theme();
<ide> }
<ide> $this->viewBuilder()->theme($theme);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function helpers($helpers = null)
<ide> return $this->viewBuilder()->helpers();
<ide> }
<ide> $this->viewBuilder()->helpers((array)$helpers, false);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function emailFormat($format = null)
<ide> throw new InvalidArgumentException('Format not available.');
<ide> }
<ide> $this->_emailFormat = $format;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function transport($name = null)
<ide> }
<ide>
<ide> $this->_transport = $transport;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _constructTransport($name)
<ide> }
<ide>
<ide> unset($config['className']);
<add>
<ide> return new $className($config);
<ide> }
<ide>
<ide> public function messageId($message = null)
<ide> }
<ide> $this->_messageId = $message;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function domain($domain = null)
<ide> return $this->_domain;
<ide> }
<ide> $this->_domain = $domain;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function attachments($attachments = null)
<ide> $attach[$name] = $fileInfo;
<ide> }
<ide> $this->_attachments = $attach;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addAttachments($attachments)
<ide> $current = $this->_attachments;
<ide> $this->attachments($attachments);
<ide> $this->_attachments = array_merge($current, $this->_attachments);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function message($type = null)
<ide> case static::MESSAGE_TEXT:
<ide> return $this->_textMessage;
<ide> }
<add>
<ide> return $this->_message;
<ide> }
<ide>
<ide> public static function configTransport($key, $config = null)
<ide> foreach ($key as $name => $settings) {
<ide> static::configTransport($name, $settings);
<ide> }
<add>
<ide> return null;
<ide> }
<ide> if (isset(static::$_transportConfig[$key])) {
<ide> public function profile($config = null)
<ide> $config = (string)$config;
<ide> }
<ide> $this->_applyConfig($config);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function send($content = null)
<ide> }
<ide> $contents = $transport->send($this);
<ide> $this->_logDelivery($contents);
<add>
<ide> return $contents;
<ide> }
<ide>
<ide> protected function _encode($text)
<ide> }
<ide> $return = mb_encode_mimeheader($text, $this->headerCharset, 'B');
<ide> mb_internal_encoding($restore);
<add>
<ide> return $return;
<ide> }
<ide>
<ide> protected function _encodeString($text, $charset)
<ide> if ($this->_appCharset === $charset) {
<ide> return $text;
<ide> }
<add>
<ide> return mb_convert_encoding($text, $charset, $this->_appCharset);
<ide> }
<ide>
<ide> protected function _wrap($message, $wrapLength = Email::LINE_LENGTH_MUST)
<ide> }
<ide> }
<ide> $formatted[] = '';
<add>
<ide> return $formatted;
<ide> }
<ide>
<ide> protected function _attachFiles($boundary = null)
<ide> $msg[] = (string)$part;
<ide> $msg[] = '';
<ide> }
<add>
<ide> return $msg;
<ide> }
<ide>
<ide> protected function _attachFiles($boundary = null)
<ide> protected function _readFile($path)
<ide> {
<ide> $File = new File($path);
<add>
<ide> return chunk_split(base64_encode($File->read()));
<ide> }
<ide>
<ide> protected function _attachInlineFiles($boundary = null)
<ide> $msg[] = (string)$part;
<ide> $msg[] = '';
<ide> }
<add>
<ide> return $msg;
<ide> }
<ide>
<ide> protected function _render($content)
<ide> $msg[] = '--' . $boundary . '--';
<ide> $msg[] = '';
<ide> }
<add>
<ide> return $msg;
<ide> }
<ide>
<ide> protected function _getTypes()
<ide> if ($this->_emailFormat === 'both') {
<ide> $types = ['html', 'text'];
<ide> }
<add>
<ide> return $types;
<ide> }
<ide>
<ide> protected function _renderTemplates($content)
<ide> foreach ($types as $type) {
<ide> $rendered[$type] = $this->_encodeString($content, $this->charset);
<ide> }
<add>
<ide> return $rendered;
<ide> }
<ide>
<ide> protected function _renderTemplates($content)
<ide> $rendered[$type] = implode("\n", $rendered[$type]);
<ide> $rendered[$type] = rtrim($rendered[$type], "\n");
<ide> }
<add>
<ide> return $rendered;
<ide> }
<ide>
<ide> protected function _getContentTransferEncoding()
<ide> if (in_array($charset, $this->_charset8bit)) {
<ide> return '8bit';
<ide> }
<add>
<ide> return '7bit';
<ide> }
<ide>
<ide> protected function _getContentTypeCharset()
<ide> if (array_key_exists($charset, $this->_contentTypeCharset)) {
<ide> return strtoupper($this->_contentTypeCharset[$charset]);
<ide> }
<add>
<ide> return strtoupper($this->charset);
<ide> }
<ide>
<ide> public function serialize()
<ide> $item = json_decode(json_encode((array)$item), true);
<ide> }
<ide> });
<add>
<ide> return serialize($array);
<ide> }
<ide>
<ide><path>src/Mailer/Mailer.php
<ide> public function getName()
<ide> join('', array_slice(explode('\\', get_class($this)), -1))
<ide> );
<ide> }
<add>
<ide> return static::$name;
<ide> }
<ide>
<ide> public function getName()
<ide> public function layout($layout)
<ide> {
<ide> $this->_email->viewBuilder()->layout($layout);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function viewBuilder()
<ide> public function __call($method, $args)
<ide> {
<ide> call_user_func_array([$this->_email, $method], $args);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function __call($method, $args)
<ide> public function set($key, $value = null)
<ide> {
<ide> $this->_email->viewVars(is_string($key) ? [$key => $value] : $key);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function send($action, $args = [], $headers = [])
<ide> protected function reset()
<ide> {
<ide> $this->_email = clone $this->_clonedEmail;
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/Mailer/Transport/DebugTransport.php
<ide> public function send(Email $email)
<ide> $headers = $email->getHeaders(['from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject']);
<ide> $headers = $this->_headersToString($headers);
<ide> $message = implode("\r\n", (array)$email->message());
<add>
<ide> return ['headers' => $headers, 'message' => $message];
<ide> }
<ide> }
<ide><path>src/Mailer/Transport/MailTransport.php
<ide> public function send(Email $email)
<ide>
<ide> $params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null;
<ide> $this->_mail($to, $subject, $message, $headers, $params);
<add>
<ide> return ['headers' => $headers, 'message' => $message];
<ide> }
<ide>
<ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> protected function _prepareFromAddress($email)
<ide> if (empty($from)) {
<ide> $from = $email->from();
<ide> }
<add>
<ide> return $from;
<ide> }
<ide>
<ide> protected function _prepareRecipientAddresses($email)
<ide> $to = $email->to();
<ide> $cc = $email->cc();
<ide> $bcc = $email->bcc();
<add>
<ide> return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
<ide> }
<ide>
<ide> protected function _prepareMessage($email)
<ide> $messages[] = $line;
<ide> }
<ide> }
<add>
<ide> return implode("\r\n", $messages);
<ide> }
<ide>
<ide> protected function _smtpSend($data, $checkCode = '250')
<ide> if ($code[2] === '-') {
<ide> continue;
<ide> }
<add>
<ide> return $code[1];
<ide> }
<ide> throw new SocketException(sprintf('SMTP Error: %s', $response));
<ide><path>src/Network/CorsBuilder.php
<ide> public function build()
<ide> if (isset($this->_headers['Access-Control-Allow-Origin'])) {
<ide> $this->_response->header($this->_headers);
<ide> }
<add>
<ide> return $this->_response;
<ide> }
<ide>
<ide> public function allowOrigin($domain)
<ide> $this->_headers['Access-Control-Allow-Origin'] = $value;
<ide> break;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> protected function _normalizeDomains($domains)
<ide> $preg = '@^' . str_replace('\*', '.*', preg_quote($preg, '@')) . '$@';
<ide> $result[] = compact('original', 'preg');
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> protected function _normalizeDomains($domains)
<ide> public function allowMethods(array $methods)
<ide> {
<ide> $this->_headers['Access-Control-Allow-Methods'] = implode(', ', $methods);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function allowMethods(array $methods)
<ide> public function allowCredentials()
<ide> {
<ide> $this->_headers['Access-Control-Allow-Credentials'] = 'true';
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function allowCredentials()
<ide> public function allowHeaders(array $headers)
<ide> {
<ide> $this->_headers['Access-Control-Allow-Headers'] = implode(', ', $headers);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function allowHeaders(array $headers)
<ide> public function exposeHeaders(array $headers)
<ide> {
<ide> $this->_headers['Access-Control-Expose-Headers'] = implode(', ', $headers);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function exposeHeaders(array $headers)
<ide> public function maxAge($age)
<ide> {
<ide> $this->_headers['Access-Control-Max-Age'] = $age;
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Network/Http/Adapter/Stream.php
<ide> public function send(Request $request, array $options)
<ide> $this->_connectionErrors = [];
<ide>
<ide> $this->_buildContext($request, $options);
<add>
<ide> return $this->_send($request);
<ide> }
<ide>
<ide> public function createResponses($headers, $content)
<ide> $body = $i == $last ? $content : '';
<ide> $responses[] = new Response($headerSlice, $body);
<ide> }
<add>
<ide> return $responses;
<ide> }
<ide>
<ide> protected function _buildContent(Request $request, $options)
<ide> }
<ide> if (is_string($content)) {
<ide> $this->_contextOptions['content'] = $content;
<add>
<ide> return;
<ide> }
<ide> if (is_array($content)) {
<ide> protected function _buildContent(Request $request, $options)
<ide> $type = $formData->contentType();
<ide> $request->header('Content-Type', $type);
<ide> $this->_contextOptions['content'] = (string)$formData;
<add>
<ide> return;
<ide> }
<ide> $this->_contextOptions['content'] = $content;
<ide> protected function _send(Request $request)
<ide> if (isset($headers['headers']) && is_array($headers['headers'])) {
<ide> $headers = $headers['headers'];
<ide> }
<add>
<ide> return $this->createResponses($headers, $content);
<ide> }
<ide>
<ide><path>src/Network/Http/Auth/Digest.php
<ide> protected function _getServerInfo(Request $request, $credentials)
<ide> if (!empty($credentials['qop']) && empty($credentials['nc'])) {
<ide> $credentials['nc'] = 1;
<ide> }
<add>
<ide> return $credentials;
<ide> }
<ide>
<ide> protected function _generateHeader(Request $request, $credentials)
<ide> if (!empty($credentials['qop'])) {
<ide> $authHeader .= ', qop="auth", nc=' . $nc . ', cnonce="' . $credentials['cnonce'] . '"';
<ide> }
<add>
<ide> return $authHeader;
<ide> }
<ide> }
<ide><path>src/Network/Http/Auth/Oauth.php
<ide> protected function _hmacSha1($request, $credentials)
<ide> $values['oauth_signature'] = base64_encode(
<ide> hash_hmac('sha1', $baseString, $key, true)
<ide> );
<add>
<ide> return $this->_buildAuth($values);
<ide> }
<ide>
<ide> public function baseString($request, $oauthValues)
<ide> $this->_normalizedParams($request, $oauthValues),
<ide> ];
<ide> $parts = array_map([$this, '_encode'], $parts);
<add>
<ide> return implode('&', $parts);
<ide> }
<ide>
<ide> protected function _normalizedUrl($url)
<ide> $out = $scheme . '://';
<ide> $out .= strtolower($parts['host']);
<ide> $out .= $parts['path'];
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _normalizedParams($request, $oauthValues)
<ide> $pairs[] = "$k=$val";
<ide> }
<ide> }
<add>
<ide> return implode('&', $pairs);
<ide> }
<ide>
<ide> protected function _buildAuth($data)
<ide> $params[] = $key . '="' . $this->_encode($value) . '"';
<ide> }
<ide> $out .= implode(',', $params);
<add>
<ide> return $out;
<ide> }
<ide>
<ide><path>src/Network/Http/Client.php
<ide> public function get($url, $data = [], array $options = [])
<ide> unset($data['_content']);
<ide> }
<ide> $url = $this->buildUrl($url, $data, $options);
<add>
<ide> return $this->_doRequest(
<ide> Request::METHOD_GET,
<ide> $url,
<ide> public function post($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_POST, $url, $data, $options);
<ide> }
<ide>
<ide> public function put($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_PUT, $url, $data, $options);
<ide> }
<ide>
<ide> public function patch($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_PATCH, $url, $data, $options);
<ide> }
<ide>
<ide> public function options($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_OPTIONS, $url, $data, $options);
<ide> }
<ide>
<ide> public function trace($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_TRACE, $url, $data, $options);
<ide> }
<ide>
<ide> public function delete($url, $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, [], $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_DELETE, $url, $data, $options);
<ide> }
<ide>
<ide> public function head($url, array $data = [], array $options = [])
<ide> {
<ide> $options = $this->_mergeOptions($options);
<ide> $url = $this->buildUrl($url, $data, $options);
<add>
<ide> return $this->_doRequest(Request::METHOD_HEAD, $url, '', $options);
<ide> }
<ide>
<ide> protected function _doRequest($method, $url, $data, $options)
<ide> $data,
<ide> $options
<ide> );
<add>
<ide> return $this->send($request, $options);
<ide> }
<ide>
<ide> public function send(Request $request, $options = [])
<ide> foreach ($responses as $response) {
<ide> $this->_cookies->store($response, $url);
<ide> }
<add>
<ide> return array_pop($responses);
<ide> }
<ide>
<ide> public function buildUrl($url, $query = [], $options = [])
<ide> $out .= ':' . $options['port'];
<ide> }
<ide> $out .= '/' . ltrim($url, '/');
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _createRequest($method, $url, $data, $options)
<ide> if (isset($options['proxy'])) {
<ide> $this->_addProxy($request, $options);
<ide> }
<add>
<ide> return $request;
<ide> }
<ide>
<ide> protected function _typeHeaders($type)
<ide> if (!isset($typeMap[$type])) {
<ide> throw new Exception("Unknown type alias '$type'.");
<ide> }
<add>
<ide> return [
<ide> 'Accept' => $typeMap[$type],
<ide> 'Content-Type' => $typeMap[$type],
<ide> protected function _createAuth($auth, $options)
<ide> sprintf('Invalid authentication type %s', $name)
<ide> );
<ide> }
<add>
<ide> return new $class($this, $options);
<ide> }
<ide> }
<ide><path>src/Network/Http/CookieCollection.php
<ide> public function get($url)
<ide> }
<ide> $out[$cookie['name']] = $cookie['value'];
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide><path>src/Network/Http/FormData.php
<ide> public function boundary()
<ide> return $this->_boundary;
<ide> }
<ide> $this->_boundary = md5(Security::randomBytes(16));
<add>
<ide> return $this->_boundary;
<ide> }
<ide>
<ide> public function add($name, $value = null)
<ide> } else {
<ide> $this->_parts[] = $this->newPart($name, $value);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addMany(array $data)
<ide> foreach ($data as $name => $value) {
<ide> $this->add($name, $value);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addFile($name, $value)
<ide> if ($filename) {
<ide> $part->filename($filename);
<ide> }
<add>
<ide> return $part;
<ide> }
<ide>
<ide> public function contentType()
<ide> if (!$this->isMultipart()) {
<ide> return 'application/x-www-form-urlencoded';
<ide> }
<add>
<ide> return 'multipart/form-data; boundary="' . $this->boundary() . '"';
<ide> }
<ide>
<ide> public function __toString()
<ide> $out .= "\r\n";
<ide> }
<ide> $out .= "--$boundary--\r\n\r\n";
<add>
<ide> return $out;
<ide> }
<ide> $data = [];
<ide> foreach ($this->_parts as $part) {
<ide> $data[$part->name()] = $part->value();
<ide> }
<add>
<ide> return http_build_query($data);
<ide> }
<ide> }
<ide><path>src/Network/Http/FormData/Part.php
<ide> public function __toString()
<ide> }
<ide> $out .= "\r\n";
<ide> $out .= (string)$this->_value;
<add>
<ide> return $out;
<ide> }
<ide> }
<ide><path>src/Network/Http/Message.php
<ide> protected function _normalizeHeader($name)
<ide> $parts = explode('-', trim($name));
<ide> $parts = array_map('strtolower', $parts);
<ide> $parts = array_map('ucfirst', $parts);
<add>
<ide> return implode('-', $parts);
<ide> }
<ide>
<ide> public function body($body = null)
<ide> return $this->_body;
<ide> }
<ide> $this->_body = $body;
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Network/Http/Request.php
<ide> public function method($method = null)
<ide> throw new Exception('Invalid method type');
<ide> }
<ide> $this->_method = $method;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function url($url = null)
<ide> return $this->_url;
<ide> }
<ide> $this->_url = $url;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function header($name = null, $value = null)
<ide> {
<ide> if ($value === null && is_string($name)) {
<ide> $name = $this->_normalizeHeader($name);
<add>
<ide> return isset($this->_headers[$name]) ? $this->_headers[$name] : null;
<ide> }
<ide> if ($value !== null && !is_array($name)) {
<ide> public function header($name = null, $value = null)
<ide> $key = $this->_normalizeHeader($key);
<ide> $this->_headers[$key] = $val;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function cookie($name, $value = null)
<ide> foreach ($name as $key => $val) {
<ide> $this->_cookies[$key] = $val;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function version($version = null)
<ide> }
<ide>
<ide> $this->_version = $version;
<add>
<ide> return $this;
<ide> }
<ide> }
<ide><path>src/Network/Http/Response.php
<ide> public function isOk()
<ide> static::STATUS_CREATED,
<ide> static::STATUS_ACCEPTED
<ide> ];
<add>
<ide> return in_array($this->_code, $codes);
<ide> }
<ide>
<ide> public function isRedirect()
<ide> static::STATUS_SEE_OTHER,
<ide> static::STATUS_TEMPORARY_REDIRECT,
<ide> ];
<add>
<ide> return (
<ide> in_array($this->_code, $codes) &&
<ide> $this->header('Location')
<ide> public function encoding()
<ide> if (empty($matches[1])) {
<ide> return null;
<ide> }
<add>
<ide> return $matches[1];
<ide> }
<ide>
<ide> public function header($name = null)
<ide> if (!isset($this->_headers[$name])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->_headers[$name];
<ide> }
<ide>
<ide> public function cookie($name = null, $all = false)
<ide> if ($all) {
<ide> return $this->_cookies[$name];
<ide> }
<add>
<ide> return $this->_cookies[$name]['value'];
<ide> }
<ide>
<ide> public function body($parser = null)
<ide> if ($parser) {
<ide> return $parser($this->_body);
<ide> }
<add>
<ide> return $this->_body;
<ide> }
<ide>
<ide> protected function _getJson()
<ide> if (!empty($this->_json)) {
<ide> return $this->_json;
<ide> }
<add>
<ide> return $this->_json = json_decode($this->_body, true);
<ide> }
<ide>
<ide> protected function _getXml()
<ide> $data = simplexml_load_string($this->_body);
<ide> if ($data) {
<ide> $this->_xml = $data;
<add>
<ide> return $this->_xml;
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function __get($name)
<ide> if (substr($key, 0, 4) === '_get') {
<ide> return $this->{$key}();
<ide> }
<add>
<ide> return $this->{$key};
<ide> }
<ide>
<ide> public function __isset($name)
<ide> $key = $this->_exposedProperties[$name];
<ide> if (substr($key, 0, 4) === '_get') {
<ide> $val = $this->{$key}();
<add>
<ide> return $val !== null;
<ide> }
<add>
<ide> return isset($this->$key);
<ide> }
<ide> }
<ide><path>src/Network/Request.php
<ide> public static function createFromGlobals()
<ide> 'session' => Session::create($sessionConfig)
<ide> ];
<ide> $config['url'] = static::_url($config);
<add>
<ide> return new static($config);
<ide> }
<ide>
<ide> protected function _processGet($query)
<ide> parse_str($querystr, $queryArgs);
<ide> $query += $queryArgs;
<ide> }
<add>
<ide> return $query;
<ide> }
<ide>
<ide> protected static function _url($config)
<ide> ) {
<ide> $uri = '/';
<ide> }
<add>
<ide> return $uri;
<ide> }
<ide>
<ide> protected static function _base()
<ide> $base = '';
<ide> }
<ide> $base = implode('/', array_map('rawurlencode', explode('/', $base)));
<add>
<ide> return [$base, $base . '/'];
<ide> }
<ide>
<ide> protected static function _base()
<ide> $webrootDir .= $webroot . '/';
<ide> }
<ide> }
<add>
<ide> return [$base . $file, $webrootDir];
<ide> }
<ide>
<ide> protected function _processFiles($post, $files)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $post;
<ide> }
<ide>
<ide> protected function _processFileData($data, $post, $path = '', $field = '')
<ide> $data = Hash::insert($data, $newPath, $fields);
<ide> }
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public function contentType()
<ide> if ($type) {
<ide> return $type;
<ide> }
<add>
<ide> return $this->env('HTTP_CONTENT_TYPE');
<ide> }
<ide>
<ide> public function session(Session $session = null)
<ide> if ($session === null) {
<ide> return $this->_session;
<ide> }
<add>
<ide> return $this->_session = $session;
<ide> }
<ide>
<ide> public function referer($local = false)
<ide> if ($ref[0] !== '/') {
<ide> $ref = '/' . $ref;
<ide> }
<add>
<ide> return $ref;
<ide> }
<ide> if (!$local) {
<ide> return $ref;
<ide> }
<ide> }
<add>
<ide> return '/';
<ide> }
<ide>
<ide> public function __call($name, $params)
<ide> {
<ide> if (strpos($name, 'is') === 0) {
<ide> $type = strtolower(substr($name, 2));
<add>
<ide> return $this->is($type);
<ide> }
<ide> throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
<ide> public function __get($name)
<ide> if (isset($this->params[$name])) {
<ide> return $this->params[$name];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function is($type)
<ide> {
<ide> if (is_array($type)) {
<ide> $result = array_map([$this, 'is'], $type);
<add>
<ide> return count(array_filter($result)) > 0;
<ide> }
<ide>
<ide> protected function _is($type)
<ide> if (isset($detect['param']) && $this->_paramDetector($detect)) {
<ide> return true;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _acceptHeaderDetector($detect)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _headerDetector($detect)
<ide> if (!is_string($value) && !is_bool($value) && is_callable($value)) {
<ide> return call_user_func($value, $header);
<ide> }
<add>
<ide> return ($header === $value);
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _paramDetector($detect)
<ide> $key = $detect['param'];
<ide> if (isset($detect['value'])) {
<ide> $value = $detect['value'];
<add>
<ide> return isset($this->params[$key]) ? $this->params[$key] == $value : false;
<ide> }
<ide> if (isset($detect['options'])) {
<ide> return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _environmentDetector($detect)
<ide> }
<ide> if (isset($detect['options'])) {
<ide> $pattern = '/' . implode('|', $detect['options']) . '/i';
<add>
<ide> return (bool)preg_match($pattern, $this->env($detect['env']));
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _environmentDetector($detect)
<ide> public function isAll(array $types)
<ide> {
<ide> $result = array_filter(array_map([$this, 'is'], $types));
<add>
<ide> return count($result) === count($types);
<ide> }
<ide>
<ide> public static function addDetector($name, $callable)
<ide> $name = strtolower($name);
<ide> if (is_callable($callable)) {
<ide> static::$_detectors[$name] = $callable;
<add>
<ide> return;
<ide> }
<ide> if (isset(static::$_detectors[$name], $callable['options'])) {
<ide> public static function addDetector($name, $callable)
<ide> public function addParams(array $params)
<ide> {
<ide> $this->params = array_merge($this->params, $params);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addPaths(array $paths)
<ide> $this->{$element} = $paths[$element];
<ide> }
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function here($base = true)
<ide> if (!$base) {
<ide> $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
<ide> }
<add>
<ide> return $url;
<ide> }
<ide>
<ide> public function header($name)
<ide> if (!in_array(strtoupper($name), ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<ide> $name = 'HTTP_' . $name;
<ide> }
<add>
<ide> return $this->env($name);
<ide> }
<ide>
<ide> public function host()
<ide> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
<ide> return $this->env('HTTP_X_FORWARDED_HOST');
<ide> }
<add>
<ide> return $this->env('HTTP_HOST');
<ide> }
<ide>
<ide> public function port()
<ide> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
<ide> return $this->env('HTTP_X_FORWARDED_PORT');
<ide> }
<add>
<ide> return $this->env('SERVER_PORT');
<ide> }
<ide>
<ide> public function scheme()
<ide> if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
<ide> return $this->env('HTTP_X_FORWARDED_PROTO');
<ide> }
<add>
<ide> return $this->env('HTTPS') ? 'https' : 'http';
<ide> }
<ide>
<ide> public function domain($tldLength = 1)
<ide> {
<ide> $segments = explode('.', $this->host());
<ide> $domain = array_slice($segments, -1 * ($tldLength + 1));
<add>
<ide> return implode('.', $domain);
<ide> }
<ide>
<ide> public function domain($tldLength = 1)
<ide> public function subdomains($tldLength = 1)
<ide> {
<ide> $segments = explode('.', $this->host());
<add>
<ide> return array_slice($segments, 0, -1 * ($tldLength + 1));
<ide> }
<ide>
<ide> public function accepts($type = null)
<ide> if ($type === null) {
<ide> return $accept;
<ide> }
<add>
<ide> return in_array($type, $accept);
<ide> }
<ide>
<ide> public function acceptLanguage($language = null)
<ide> if ($language === null) {
<ide> return $accept;
<ide> }
<add>
<ide> return in_array(strtolower($language), $accept);
<ide> }
<ide>
<ide> protected function _parseAcceptWithQualifier($header)
<ide> }
<ide> }
<ide> krsort($accept);
<add>
<ide> return $accept;
<ide> }
<ide>
<ide> public function data($name = null)
<ide> $args = func_get_args();
<ide> if (count($args) === 2) {
<ide> $this->data = Hash::insert($this->data, $name, $args[1]);
<add>
<ide> return $this;
<ide> }
<ide> if ($name !== null) {
<ide> return Hash::get($this->data, $name);
<ide> }
<add>
<ide> return $this->data;
<ide> }
<ide>
<ide> public function param($name)
<ide> $args = func_get_args();
<ide> if (count($args) === 2) {
<ide> $this->params = Hash::insert($this->params, $name, $args[1]);
<add>
<ide> return $this;
<ide> }
<ide> if (!isset($this->params[$name])) {
<ide> return Hash::get($this->params, $name, false);
<ide> }
<add>
<ide> return $this->params[$name];
<ide> }
<ide>
<ide> public function input($callback = null)
<ide> if (!empty($args)) {
<ide> $callback = array_shift($args);
<ide> array_unshift($args, $input);
<add>
<ide> return call_user_func_array($callback, $args);
<ide> }
<add>
<ide> return $input;
<ide> }
<ide>
<ide> public function cookie($key)
<ide> if (isset($this->cookies[$key])) {
<ide> return $this->cookies[$key];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function env($key, $value = null, $default = null)
<ide> if ($value !== null) {
<ide> $this->_environment[$key] = $value;
<ide> $this->clearDetectorCache();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> $key = strtoupper($key);
<ide> if (!array_key_exists($key, $this->_environment)) {
<ide> $this->_environment[$key] = env($key);
<ide> }
<add>
<ide> return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
<ide> }
<ide>
<ide> protected function _readInput()
<ide> fclose($fh);
<ide> $this->_input = $content;
<ide> }
<add>
<ide> return $this->_input;
<ide> }
<ide>
<ide> public function offsetGet($name)
<ide> if ($name === 'data') {
<ide> return $this->data;
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function offsetExists($name)
<ide> if ($name === 'url' || $name === 'data') {
<ide> return true;
<ide> }
<add>
<ide> return isset($this->params[$name]);
<ide> }
<ide>
<ide><path>src/Network/Response.php
<ide> public function header($header = null, $value = null)
<ide> }
<ide> $this->_headers[$header] = is_array($value) ? array_map('trim', $value) : trim($value);
<ide> }
<add>
<ide> return $this->_headers;
<ide> }
<ide>
<ide> public function location($url = null)
<ide> {
<ide> if ($url === null) {
<ide> $headers = $this->header();
<add>
<ide> return isset($headers['Location']) ? $headers['Location'] : null;
<ide> }
<ide> $this->header('Location', $url);
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function body($content = null)
<ide> if ($content === null) {
<ide> return $this->_body;
<ide> }
<add>
<ide> return $this->_body = $content;
<ide> }
<ide>
<ide> public function statusCode($code = null)
<ide> if (!isset($this->_statusCodes[$code])) {
<ide> throw new InvalidArgumentException('Unknown status code');
<ide> }
<add>
<ide> return $this->_status = $code;
<ide> }
<ide>
<ide> public function httpCodes($code = null)
<ide> throw new InvalidArgumentException('Invalid status code');
<ide> }
<ide> $this->_statusCodes = $code + $this->_statusCodes;
<add>
<ide> return true;
<ide> }
<ide> if (!isset($this->_statusCodes[$code])) {
<ide> return null;
<ide> }
<add>
<ide> return [$code => $this->_statusCodes[$code]];
<ide> }
<ide>
<ide> public function type($contentType = null)
<ide> foreach ($contentType as $type => $definition) {
<ide> $this->_mimeTypes[$type] = $definition;
<ide> }
<add>
<ide> return $this->_contentType;
<ide> }
<ide> if (isset($this->_mimeTypes[$contentType])) {
<ide> public function type($contentType = null)
<ide> if (strpos($contentType, '/') === false) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_contentType = $contentType;
<ide> }
<ide>
<ide> public function getMimeType($alias)
<ide> if (isset($this->_mimeTypes[$alias])) {
<ide> return $this->_mimeTypes[$alias];
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function mapType($ctype)
<ide> return $alias;
<ide> }
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function charset($charset = null)
<ide> if ($charset === null) {
<ide> return $this->_charset;
<ide> }
<add>
<ide> return $this->_charset = $charset;
<ide> }
<ide>
<ide> public function sharable($public = null, $time = null)
<ide> return null;
<ide> }
<ide> $sharable = $public || !($private || $noCache);
<add>
<ide> return $sharable;
<ide> }
<ide> if ($public) {
<ide> public function sharable($public = null, $time = null)
<ide> if (!$time) {
<ide> $this->_setCacheControl();
<ide> }
<add>
<ide> return (bool)$public;
<ide> }
<ide>
<ide> public function sharedMaxAge($seconds = null)
<ide> if (isset($this->_cacheDirectives['s-maxage'])) {
<ide> return $this->_cacheDirectives['s-maxage'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function maxAge($seconds = null)
<ide> if (isset($this->_cacheDirectives['max-age'])) {
<ide> return $this->_cacheDirectives['max-age'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function mustRevalidate($enable = null)
<ide> }
<ide> $this->_setCacheControl();
<ide> }
<add>
<ide> return array_key_exists('must-revalidate', $this->_cacheDirectives);
<ide> }
<ide>
<ide> public function expires($time = null)
<ide> if (isset($this->_headers['Expires'])) {
<ide> return $this->_headers['Expires'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function modified($time = null)
<ide> if (isset($this->_headers['Last-Modified'])) {
<ide> return $this->_headers['Last-Modified'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function vary($cacheVariances = null)
<ide> if (isset($this->_headers['Vary'])) {
<ide> return explode(', ', $this->_headers['Vary']);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function etag($hash = null, $weak = false)
<ide> if (isset($this->_headers['Etag'])) {
<ide> return $this->_headers['Etag'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> protected function _getUTCDate($time = null)
<ide> $result = new DateTime($time);
<ide> }
<ide> $result->setTimeZone(new DateTimeZone('UTC'));
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function compress()
<ide> $compressionEnabled = ini_get("zlib.output_compression") !== '1' &&
<ide> extension_loaded("zlib") &&
<ide> (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
<add>
<ide> return $compressionEnabled && ob_start('ob_gzhandler');
<ide> }
<ide>
<ide> public function protocol($protocol = null)
<ide> if ($protocol !== null) {
<ide> $this->_protocol = $protocol;
<ide> }
<add>
<ide> return $this->_protocol;
<ide> }
<ide>
<ide> public function length($bytes = null)
<ide> if (isset($this->_headers['Content-Length'])) {
<ide> return $this->_headers['Content-Length'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function checkNotModified(Request $request)
<ide> if ($notModified) {
<ide> $this->notModified();
<ide> }
<add>
<ide> return $notModified;
<ide> }
<ide>
<ide> public function __toString()
<ide> if (!is_string($this->_body) && is_callable($this->_body)) {
<ide> return '';
<ide> }
<add>
<ide> return (string)$this->_body;
<ide> }
<ide>
<ide> public function cookie($options = null)
<ide> if (!isset($this->_cookies[$options])) {
<ide> return null;
<ide> }
<add>
<ide> return $this->_cookies[$options];
<ide> }
<ide>
<ide> public function cors(Request $request, $allowedDomains = [], $allowedMethods = [
<ide> ->allowMethods((array)$allowedMethods)
<ide> ->allowHeaders((array)$allowedHeaders)
<ide> ->build();
<add>
<ide> return $builder;
<ide> }
<ide>
<ide> protected function _fileRange($file, $httpRange)
<ide> $this->header([
<ide> 'Content-Range' => 'bytes 0-' . $lastByte . '/' . $fileSize
<ide> ]);
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _sendFile($file, $range)
<ide> while (!feof($file->handle)) {
<ide> if (!$this->_isActive()) {
<ide> $file->close();
<add>
<ide> return false;
<ide> }
<ide> $offset = $file->offset();
<ide> protected function _sendFile($file, $range)
<ide> echo fread($file->handle, $bufferSize);
<ide> }
<ide> $file->close();
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>src/Network/Session.php
<ide> public function start()
<ide>
<ide> if ($this->_isCLI) {
<ide> $_SESSION = [];
<add>
<ide> return $this->_started = true;
<ide> }
<ide>
<ide> public function start()
<ide>
<ide> if ($this->_timedOut()) {
<ide> $this->destroy();
<add>
<ide> return $this->start();
<ide> }
<ide>
<ide> public function consume($name)
<ide> if ($value !== null) {
<ide> $this->_overwrite($_SESSION, Hash::remove($_SESSION, $name));
<ide> }
<add>
<ide> return $value;
<ide> }
<ide>
<ide> protected function _timedOut()
<ide> }
<ide>
<ide> $this->write('Config.time', time());
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>src/Network/Session/CacheSession.php
<ide> public function destroy($id)
<ide> public function gc($maxlifetime)
<ide> {
<ide> Cache::gc($this->_options['config'], time() - $maxlifetime);
<add>
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Network/Session/DatabaseSession.php
<ide> public function write($id, $data)
<ide> $record = compact('data', 'expires');
<ide> $record[$this->_table->primaryKey()] = $id;
<ide> $result = $this->_table->save(new Entity($record));
<add>
<ide> return (bool)$result;
<ide> }
<ide>
<ide> public function destroy($id)
<ide> public function gc($maxlifetime)
<ide> {
<ide> $this->_table->deleteAll(['expires <' => time()]);
<add>
<ide> return true;
<ide> }
<ide> }
<ide><path>src/Network/Socket.php
<ide> public function connect()
<ide> if ($this->connected) {
<ide> stream_set_timeout($this->connection, $this->_config['timeout']);
<ide> }
<add>
<ide> return $this->connected;
<ide> }
<ide>
<ide> public function context()
<ide> if (!$this->connection) {
<ide> return null;
<ide> }
<add>
<ide> return stream_context_get_options($this->connection);
<ide> }
<ide>
<ide> public function host()
<ide> if (Validation::ip($this->_config['host'])) {
<ide> return gethostbyaddr($this->_config['host']);
<ide> }
<add>
<ide> return gethostbyaddr($this->address());
<ide> }
<ide>
<ide> public function address()
<ide> if (Validation::ip($this->_config['host'])) {
<ide> return $this->_config['host'];
<ide> }
<add>
<ide> return gethostbyname($this->_config['host']);
<ide> }
<ide>
<ide> public function addresses()
<ide> if (Validation::ip($this->_config['host'])) {
<ide> return [$this->_config['host']];
<ide> }
<add>
<ide> return gethostbynamel($this->_config['host']);
<ide> }
<ide>
<ide> public function lastError()
<ide> if (!empty($this->lastError)) {
<ide> return $this->lastError['num'] . ': ' . $this->lastError['str'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function write($data)
<ide> return $written;
<ide> }
<ide> }
<add>
<ide> return $written;
<ide> }
<ide>
<ide> public function read($length = 1024)
<ide> $info = stream_get_meta_data($this->connection);
<ide> if ($info['timed_out']) {
<ide> $this->setLastError(E_WARNING, 'Connection timed out');
<add>
<ide> return false;
<ide> }
<add>
<ide> return $buffer;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function disconnect()
<ide> {
<ide> if (!is_resource($this->connection)) {
<ide> $this->connected = false;
<add>
<ide> return true;
<ide> }
<ide> $this->connected = !fclose($this->connection);
<ide>
<ide> if (!$this->connected) {
<ide> $this->connection = null;
<ide> }
<add>
<ide> return !$this->connected;
<ide> }
<ide>
<ide> public function reset($state = null)
<ide> foreach ($state as $property => $value) {
<ide> $this->{$property} = $value;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true)
<ide> }
<ide> if ($enableCryptoResult === true) {
<ide> $this->encrypted = $enable;
<add>
<ide> return true;
<ide> }
<ide> $errorMessage = 'Unable to perform enableCrypto operation on the current socket';
<ide><path>src/ORM/Association.php
<ide> public function name($name = null)
<ide> if ($name !== null) {
<ide> $this->_name = $name;
<ide> }
<add>
<ide> return $this->_name;
<ide> }
<ide>
<ide> public function cascadeCallbacks($cascadeCallbacks = null)
<ide> if ($cascadeCallbacks !== null) {
<ide> $this->_cascadeCallbacks = $cascadeCallbacks;
<ide> }
<add>
<ide> return $this->_cascadeCallbacks;
<ide> }
<ide>
<ide> public function source(Table $table = null)
<ide> if ($table === null) {
<ide> return $this->_sourceTable;
<ide> }
<add>
<ide> return $this->_sourceTable = $table;
<ide> }
<ide>
<ide> public function conditions($conditions = null)
<ide> if ($conditions !== null) {
<ide> $this->_conditions = $conditions;
<ide> }
<add>
<ide> return $this->_conditions;
<ide> }
<ide>
<ide> public function foreignKey($key = null)
<ide> if ($key !== null) {
<ide> $this->_foreignKey = $key;
<ide> }
<add>
<ide> return $this->_foreignKey;
<ide> }
<ide>
<ide> public function dependent($dependent = null)
<ide> if ($dependent !== null) {
<ide> $this->_dependent = $dependent;
<ide> }
<add>
<ide> return $this->_dependent;
<ide> }
<ide>
<ide> public function dependent($dependent = null)
<ide> public function canBeJoined(array $options = [])
<ide> {
<ide> $strategy = isset($options['strategy']) ? $options['strategy'] : $this->strategy();
<add>
<ide> return $strategy == $this::STRATEGY_JOIN;
<ide> }
<ide>
<ide> public function joinType($type = null)
<ide> if ($type === null) {
<ide> return $this->_joinType;
<ide> }
<add>
<ide> return $this->_joinType = $type;
<ide> }
<ide>
<ide> public function property($name = null)
<ide> );
<ide> }
<ide> }
<add>
<ide> return $this->_propertyName;
<ide> }
<ide>
<ide> public function property($name = null)
<ide> protected function _propertyName()
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<add>
<ide> return Inflector::underscore($name);
<ide> }
<ide>
<ide> public function strategy($name = null)
<ide> }
<ide> $this->_strategy = $name;
<ide> }
<add>
<ide> return $this->_strategy;
<ide> }
<ide>
<ide> public function finder($finder = null)
<ide> if ($finder !== null) {
<ide> $this->_finder = $finder;
<ide> }
<add>
<ide> return $this->_finder;
<ide> }
<ide>
<ide> protected function _appendNotMatching($query, $options)
<ide> $primaryKey = $query->aliasFields((array)$target->primaryKey(), $this->_name);
<ide> $query->andWhere(function ($exp) use ($primaryKey) {
<ide> array_map([$exp, 'isNull'], $primaryKey);
<add>
<ide> return $exp;
<ide> });
<ide> }
<ide> public function transformRow($row, $nestKey, $joined)
<ide> $row[$sourceAlias][$this->property()] = $row[$nestKey];
<ide> unset($row[$nestKey]);
<ide> }
<add>
<ide> return $row;
<ide> }
<ide>
<ide> public function defaultRowValue($row, $joined)
<ide> if (isset($row[$sourceAlias])) {
<ide> $row[$sourceAlias][$this->property()] = null;
<ide> }
<add>
<ide> return $row;
<ide> }
<ide>
<ide> public function find($type = null, array $options = [])
<ide> {
<ide> $type = $type ?: $this->finder();
<ide> list($type, $opts) = $this->_extractFinder($type);
<add>
<ide> return $this->target()
<ide> ->find($type, $options + $opts)
<ide> ->where($this->conditions());
<ide> public function updateAll($fields, $conditions)
<ide> ->where($this->conditions())
<ide> ->where($conditions)
<ide> ->clause('where');
<add>
<ide> return $target->updateAll($fields, $expression);
<ide> }
<ide>
<ide> public function deleteAll($conditions)
<ide> ->where($this->conditions())
<ide> ->where($conditions)
<ide> ->clause('where');
<add>
<ide> return $target->deleteAll($expression);
<ide> }
<ide>
<ide> protected function _formatAssociationResults($query, $surrogate, $options)
<ide> foreach ($formatters as $callable) {
<ide> $extracted = new ResultSetDecorator($callable($extracted));
<ide> }
<add>
<ide> return $results->insert($property, $extracted);
<ide> }, Query::PREPEND);
<ide> }
<ide><path>src/ORM/Association/BelongsTo.php
<ide> public function foreignKey($key = null)
<ide> if ($this->_foreignKey === null) {
<ide> $this->_foreignKey = $this->_modelKey($this->target()->alias());
<ide> }
<add>
<ide> return $this->_foreignKey;
<ide> }
<add>
<ide> return parent::foreignKey($key);
<ide> }
<ide>
<ide> public function cascadeDelete(EntityInterface $entity, array $options = [])
<ide> protected function _propertyName()
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<add>
<ide> return Inflector::underscore(Inflector::singularize($name));
<ide> }
<ide>
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> $targetEntity->extract((array)$this->bindingKey())
<ide> );
<ide> $entity->set($properties, ['guard' => false]);
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> }
<ide> $resultMap[implode(';', $values)] = $result;
<ide> }
<add>
<ide> return $resultMap;
<ide> }
<ide> }
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function targetForeignKey($key = null)
<ide> if ($this->_targetForeignKey === null) {
<ide> $this->_targetForeignKey = $this->_modelKey($this->target()->alias());
<ide> }
<add>
<ide> return $this->_targetForeignKey;
<ide> }
<add>
<ide> return $this->_targetForeignKey = $key;
<ide> }
<ide>
<ide> public function junction($table = null)
<ide> $this->_generateSourceAssociations($table, $source);
<ide> $this->_generateTargetAssociations($table, $source, $target);
<ide> $this->_generateJunctionAssociations($table, $source, $target);
<add>
<ide> return $this->_junctionTable = $table;
<ide> }
<ide>
<ide> protected function _appendNotMatching($query, $options)
<ide> $primaryKey = $query->aliasFields((array)$target->primaryKey(), $target->alias());
<ide> $query->andWhere(function ($exp) use ($primaryKey) {
<ide> array_map([$exp, 'isNull'], $primaryKey);
<add>
<ide> return $exp;
<ide> });
<ide> }
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> }
<ide> $resultMap[implode(';', $values)][] = $result;
<ide> }
<add>
<ide> return $resultMap;
<ide> }
<ide>
<ide> public function cascadeDelete(EntityInterface $entity, array $options = [])
<ide> foreach ($hasMany->find('all')->where($conditions)->toList() as $related) {
<ide> $table->delete($related, $options);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> $conditions = array_merge($conditions, $hasMany->conditions());
<add>
<ide> return $table->deleteAll($conditions);
<ide> }
<ide>
<ide> public function saveStrategy($strategy = null)
<ide> $msg = sprintf('Invalid save strategy "%s"', $strategy);
<ide> throw new InvalidArgumentException($msg);
<ide> }
<add>
<ide> return $this->_saveStrategy = $strategy;
<ide> }
<ide>
<ide> protected function _saveTarget(EntityInterface $parentEntity, $entities, $option
<ide>
<ide> if (!empty($options['atomic'])) {
<ide> $original[$k]->errors($entity->errors());
<add>
<ide> return false;
<ide> }
<ide> }
<ide> protected function _saveTarget(EntityInterface $parentEntity, $entities, $option
<ide> $success = $this->_saveLinks($parentEntity, $persisted, $options);
<ide> if (!$success && !empty($options['atomic'])) {
<ide> $parentEntity->set($this->property(), $original);
<add>
<ide> return false;
<ide> }
<ide>
<ide> $parentEntity->set($this->property(), $entities);
<add>
<ide> return $parentEntity;
<ide> }
<ide>
<ide> public function conditions($conditions = null)
<ide> $this->_conditions = $conditions;
<ide> $this->_targetConditions = $this->_junctionConditions = null;
<ide> }
<add>
<ide> return $this->_conditions;
<ide> }
<ide>
<ide> protected function targetConditions()
<ide> $matching[$field] = $value;
<ide> }
<ide> }
<add>
<ide> return $this->_targetConditions = $matching;
<ide> }
<ide>
<ide> protected function junctionConditions()
<ide> $matching[$field] = $value;
<ide> }
<ide> }
<add>
<ide> return $this->_junctionConditions = $matching;
<ide> }
<ide>
<ide> public function find($type = null, array $options = [])
<ide> 'foreignKey' => $this->targetForeignKey()
<ide> ]);
<ide> $conditions += $this->junctionConditions();
<add>
<ide> return $this->_appendJunctionJoin($query, $conditions);
<ide> }
<ide>
<ide> protected function _appendJunctionJoin($query, $conditions)
<ide> ->addDefaultTypes($assoc->target())
<ide> ->join($matching + $joins, [], true);
<ide> $query->eagerLoader()->addToJoinsMap($name, $assoc);
<add>
<ide> return $query;
<ide> }
<ide>
<ide> function () use ($sourceEntity, $targetEntities, $primaryValue, $options) {
<ide> ksort($targetEntities);
<ide> $sourceEntity->set($property, array_values($targetEntities));
<ide> $sourceEntity->dirty($property, false);
<add>
<ide> return true;
<ide> }
<ide> );
<ide> protected function _buildQuery($options)
<ide> ->select($query->aliasFields((array)$assoc->foreignKey(), $name));
<ide>
<ide> $assoc->attachTo($query);
<add>
<ide> return $query;
<ide> }
<ide>
<ide> protected function _junctionAssociationName()
<ide> ->association($this->junction()->alias())
<ide> ->name();
<ide> }
<add>
<ide> return $this->_junctionAssociationName;
<ide> }
<ide>
<ide> protected function _junctionTableName($name = null)
<ide> sort($tablesNames);
<ide> $this->_junctionTableName = implode('_', $tablesNames);
<ide> }
<add>
<ide> return $this->_junctionTableName;
<ide> }
<add>
<ide> return $this->_junctionTableName = $name;
<ide> }
<ide>
<ide><path>src/ORM/Association/DependentDeleteTrait.php
<ide> public function cascadeDelete(EntityInterface $entity, array $options = [])
<ide> foreach ($this->find()->where($conditions)->toList() as $related) {
<ide> $table->delete($related, $options);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> $conditions = array_merge($conditions, $this->conditions());
<add>
<ide> return $table->deleteAll($conditions);
<ide> }
<ide> }
<ide><path>src/ORM/Association/ExternalAssociationTrait.php
<ide> public function foreignKey($key = null)
<ide> if ($this->_foreignKey === null) {
<ide> $this->_foreignKey = $this->_modelKey($this->source()->table());
<ide> }
<add>
<ide> return $this->_foreignKey;
<ide> }
<add>
<ide> return parent::foreignKey($key);
<ide> }
<ide>
<ide> public function sort($sort = null)
<ide> if ($sort !== null) {
<ide> $this->_sort = $sort;
<ide> }
<add>
<ide> return $this->_sort;
<ide> }
<ide>
<ide> public function defaultRowValue($row, $joined)
<ide> if (isset($row[$sourceAlias])) {
<ide> $row[$sourceAlias][$this->property()] = $joined ? null : [];
<ide> }
<add>
<ide> return $row;
<ide> }
<ide>
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> }
<ide> $resultMap[implode(';', $values)][] = $result;
<ide> }
<add>
<ide> return $resultMap;
<ide> }
<ide>
<ide><path>src/ORM/Association/HasMany.php
<ide> public function saveStrategy($strategy = null)
<ide> $msg = sprintf('Invalid save strategy "%s"', $strategy);
<ide> throw new InvalidArgumentException($msg);
<ide> }
<add>
<ide> return $this->_saveStrategy = $strategy;
<ide> }
<ide>
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> if (!empty($options['atomic'])) {
<ide> $original[$k]->errors($targetEntity->errors());
<ide> $entity->set($this->property(), $original);
<add>
<ide> return false;
<ide> }
<ide> }
<ide>
<ide> $entity->set($this->property(), $targetEntities);
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> public function replace(EntityInterface $sourceEntity, array $targetEntities, ar
<ide> $sourceEntity = $result;
<ide> }
<ide> $this->saveStrategy($saveStrategy);
<add>
<ide> return $ok;
<ide> }
<ide>
<ide> protected function _unlink(array $foreignKey, Table $target, array $conditions =
<ide> foreach ($query as $assoc) {
<ide> $ok = $ok && $target->delete($assoc, $options);
<ide> }
<add>
<ide> return $ok;
<ide> }
<ide>
<ide> $target->deleteAll($conditions);
<add>
<ide> return true;
<ide> }
<ide>
<ide> $updateFields = array_fill_keys($foreignKey, null);
<ide> $target->updateAll($updateFields, $conditions);
<add>
<ide> return true;
<ide> }
<ide>
<ide><path>src/ORM/Association/HasOne.php
<ide> public function foreignKey($key = null)
<ide> if ($this->_foreignKey === null) {
<ide> $this->_foreignKey = $this->_modelKey($this->source()->alias());
<ide> }
<add>
<ide> return $this->_foreignKey;
<ide> }
<add>
<ide> return parent::foreignKey($key);
<ide> }
<ide>
<ide> public function foreignKey($key = null)
<ide> protected function _propertyName()
<ide> {
<ide> list(, $name) = pluginSplit($this->_name);
<add>
<ide> return Inflector::underscore(Inflector::singularize($name));
<ide> }
<ide>
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide>
<ide> if (!$this->target()->save($targetEntity, $options)) {
<ide> $targetEntity->unsetProperty(array_keys($properties));
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> }
<ide> $resultMap[implode(';', $values)] = $result;
<ide> }
<add>
<ide> return $resultMap;
<ide> }
<ide> }
<ide><path>src/ORM/Association/SelectableAssociationTrait.php
<ide> trait SelectableAssociationTrait
<ide> public function requiresKeys(array $options = [])
<ide> {
<ide> $strategy = isset($options['strategy']) ? $options['strategy'] : $this->strategy();
<add>
<ide> return $strategy === $this::STRATEGY_SELECT;
<ide> }
<ide>
<ide> public function eagerLoader(array $options)
<ide> $options += $this->_defaultOptions();
<ide> $fetchQuery = $this->_buildQuery($options);
<ide> $resultMap = $this->_buildResultMap($fetchQuery, $options);
<add>
<ide> return $this->_resultInjector($fetchQuery, $resultMap, $options);
<ide> }
<ide>
<ide> public function _addFilteringJoin($query, $key, $subquery)
<ide> }
<ide>
<ide> $conditions = isset($conditions) ? $conditions : $query->newExpr([$key => $filter]);
<add>
<ide> return $query->innerJoin(
<ide> [$aliasedTable => $subquery],
<ide> $conditions
<ide> protected function _addFilteringCondition($query, $key, $filter)
<ide> }
<ide>
<ide> $conditions = isset($conditions) ? $conditions : [$key . ' IN' => $filter];
<add>
<ide> return $query->andWhere($conditions);
<ide> }
<ide>
<ide> protected function _createTupleCondition($query, $keys, $filter, $operator)
<ide> $types[] = $defaults[$k];
<ide> }
<ide> }
<add>
<ide> return new TupleComparison($keys, $filter, $types, $operator);
<ide> }
<ide>
<ide> protected function _buildSubquery($query)
<ide>
<ide> $fields = $this->_subqueryFields($query);
<ide> $filterQuery->select($fields['select'], true)->group($fields['group']);
<add>
<ide> return $filterQuery;
<ide> }
<ide>
<ide> protected function _subqueryFields($query)
<ide> }
<ide> });
<ide> }
<add>
<ide> return ['select' => $fields, 'group' => $group];
<ide> }
<ide>
<ide> protected function _resultInjector($fetchQuery, $resultMap, $options)
<ide> }
<ide>
<ide> $sourceKey = $sourceKeys[0];
<add>
<ide> return function ($row) use ($resultMap, $sourceKey, $nestKey) {
<ide> if (isset($row[$sourceKey], $resultMap[$row[$sourceKey]])) {
<ide> $row[$nestKey] = $resultMap[$row[$sourceKey]];
<ide> }
<add>
<ide> return $row;
<ide> };
<ide> }
<ide> protected function _multiKeysInjector($resultMap, $sourceKeys, $nestKey)
<ide> if (isset($resultMap[$key])) {
<ide> $row[$nestKey] = $resultMap[$key];
<ide> }
<add>
<ide> return $row;
<ide> };
<ide> }
<ide><path>src/ORM/AssociationCollection.php
<ide> class AssociationCollection implements IteratorAggregate
<ide> public function add($alias, Association $association)
<ide> {
<ide> list(, $alias) = pluginSplit($alias);
<add>
<ide> return $this->_items[strtolower($alias)] = $association;
<ide> }
<ide>
<ide> public function get($alias)
<ide> if (isset($this->_items[$alias])) {
<ide> return $this->_items[$alias];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function getByProperty($prop)
<ide> return $assoc;
<ide> }
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function type($class)
<ide>
<ide> $out = array_filter($this->_items, function ($assoc) use ($class) {
<ide> list(, $name) = namespaceSplit(get_class($assoc));
<add>
<ide> return in_array(strtolower($name), $class, true);
<ide> });
<add>
<ide> return array_values($out);
<ide> }
<ide>
<ide> public function saveParents(Table $table, EntityInterface $entity, $associations
<ide> if (empty($associations)) {
<ide> return true;
<ide> }
<add>
<ide> return $this->_saveAssociations($table, $entity, $associations, $options, false);
<ide> }
<ide>
<ide> public function saveChildren(Table $table, EntityInterface $entity, array $assoc
<ide> if (empty($associations)) {
<ide> return true;
<ide> }
<add>
<ide> return $this->_saveAssociations($table, $entity, $associations, $options, true);
<ide> }
<ide>
<ide> protected function _saveAssociations($table, $entity, $associations, $options, $
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _save($association, $entity, $nested, $options)
<ide> if (!empty($nested)) {
<ide> $options = (array)$nested + $options;
<ide> }
<add>
<ide> return (bool)$association->saveAssociated($entity, $options);
<ide> }
<ide>
<ide><path>src/ORM/Behavior.php
<ide> protected function _resolveMethodAliases($key, $defaults, $config)
<ide> if (isset($config[$key]) && $config[$key] === []) {
<ide> $this->config($key, [], false);
<ide> unset($config[$key]);
<add>
<ide> return $config;
<ide> }
<ide>
<ide> protected function _resolveMethodAliases($key, $defaults, $config)
<ide> }
<ide> $this->config($key, array_flip($indexedCustom), false);
<ide> unset($config[$key]);
<add>
<ide> return $config;
<ide> }
<ide>
<ide> public function implementedEvents()
<ide> ];
<ide> }
<ide> }
<add>
<ide> return $events;
<ide> }
<ide>
<ide><path>src/ORM/Behavior/Translate/TranslateTrait.php
<ide> public function translation($language)
<ide>
<ide> // Assume the user will modify any of the internal translations, helps with saving
<ide> $this->dirty('_translations', true);
<add>
<ide> return $i18n[$language];
<ide> }
<ide> }
<ide><path>src/ORM/Behavior/TranslateBehavior.php
<ide> public function locale($locale = null)
<ide> if ($locale === null) {
<ide> return $this->_locale ?: I18n::locale();
<ide> }
<add>
<ide> return $this->_locale = (string)$locale;
<ide> }
<ide>
<ide> public function findTranslations(Query $query, array $options)
<ide> {
<ide> $locales = isset($options['locales']) ? $options['locales'] : [];
<ide> $targetAlias = $this->_translationTable->alias();
<add>
<ide> return $query
<ide> ->contain([$targetAlias => function ($q) use ($locales, $targetAlias) {
<ide> if ($locales) {
<ide> $q->where(["$targetAlias.locale IN" => $locales]);
<ide> }
<add>
<ide> return $q;
<ide> }])
<ide> ->formatResults([$this, 'groupTranslations'], $query::PREPEND);
<ide> public function groupTranslations($results)
<ide> $row->set('_translations', $result, $options);
<ide> unset($row['_i18n']);
<ide> $row->clean();
<add>
<ide> return $row;
<ide> });
<ide> }
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> public function beforeSave(Event $event, EntityInterface $entity)
<ide> if ($level) {
<ide> $entity->set($level, $parentNode[$level] + 1);
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> public function beforeSave(Event $event, EntityInterface $entity)
<ide> if ($level) {
<ide> $entity->set($level, 0);
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> public function beforeSave(Event $event, EntityInterface $entity)
<ide> $parentNode = $this->_getNode($parent);
<ide> $entity->set($level, $parentNode[$level] + 1);
<ide> }
<add>
<ide> return;
<ide> }
<ide>
<ide> function ($exp) use ($config) {
<ide> $leftInverse = clone $exp;
<ide> $leftInverse->type('*')->add('-1');
<ide> $rightInverse = clone $leftInverse;
<add>
<ide> return $exp
<ide> ->eq($config['leftField'], $leftInverse->add($config['leftField']))
<ide> ->eq($config['rightField'], $rightInverse->add($config['rightField']));
<ide> public function childCount(EntityInterface $node, $direct = false)
<ide> }
<ide>
<ide> $this->_ensureFields($node);
<add>
<ide> return ($node->get($config['right']) - $node->get($config['left']) - 1) / 2;
<ide> }
<ide>
<ide> function ($field) {
<ide> }
<ide>
<ide> $node = $this->_getNode($for);
<add>
<ide> return $this->_scope($query)
<ide> ->where([
<ide> "{$right} <" => $node->get($config['right']),
<ide> public function findTreeList(Query $query, array $options)
<ide> 'parentField' => $this->config('parent'),
<ide> 'order' => [$this->config('left') => 'ASC']
<ide> ]);
<add>
<ide> return $this->formatTreeList($results, $options);
<ide> }
<ide>
<ide> public function formatTreeList(Query $query, array $options = [])
<ide> 'valuePath' => $this->_table->displayField(),
<ide> 'spacer' => '_'
<ide> ];
<add>
<ide> return $results
<ide> ->listNested()
<ide> ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
<ide> public function removeFromTree(EntityInterface $node)
<ide> {
<ide> return $this->_table->connection()->transactional(function () use ($node) {
<ide> $this->_ensureFields($node);
<add>
<ide> return $this->_removeFromTree($node);
<ide> });
<ide> }
<ide> protected function _removeFromTree($node)
<ide> foreach ($fields as $field) {
<ide> $node->dirty($field, false);
<ide> }
<add>
<ide> return $node;
<ide> }
<ide>
<ide> public function moveUp(EntityInterface $node, $number = 1)
<ide>
<ide> return $this->_table->connection()->transactional(function () use ($node, $number) {
<ide> $this->_ensureFields($node);
<add>
<ide> return $this->_moveUp($node, $number);
<ide> });
<ide> }
<ide> public function moveDown(EntityInterface $node, $number = 1)
<ide>
<ide> return $this->_table->connection()->transactional(function () use ($node, $number) {
<ide> $this->_ensureFields($node);
<add>
<ide> return $this->_moveDown($node, $number);
<ide> });
<ide> }
<ide> protected function _getPrimaryKey()
<ide> $this->_primaryKey = (array)$this->_table->primaryKey();
<ide> $this->_primaryKey = $this->_primaryKey[0];
<ide> }
<add>
<ide> return $this->_primaryKey;
<ide> }
<ide>
<ide><path>src/ORM/BehaviorRegistry.php
<ide> protected function _resolveClassName($class)
<ide> if (!$result) {
<ide> $result = App::className($class, 'ORM/Behavior', 'Behavior');
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> protected function _create($class, $alias, $config)
<ide> $methods = $this->_getMethods($instance, $class, $alias);
<ide> $this->_methodMap += $methods['methods'];
<ide> $this->_finderMap += $methods['finders'];
<add>
<ide> return $instance;
<ide> }
<ide>
<ide> protected function _getMethods(Behavior $instance, $class, $alias)
<ide> public function hasMethod($method)
<ide> {
<ide> $method = strtolower($method);
<add>
<ide> return isset($this->_methodMap[$method]);
<ide> }
<ide>
<ide> public function hasMethod($method)
<ide> public function hasFinder($method)
<ide> {
<ide> $method = strtolower($method);
<add>
<ide> return isset($this->_finderMap[$method]);
<ide> }
<ide>
<ide> public function call($method, array $args = [])
<ide> $method = strtolower($method);
<ide> if ($this->hasMethod($method) && $this->has($this->_methodMap[$method][0])) {
<ide> list($behavior, $callMethod) = $this->_methodMap[$method];
<add>
<ide> return call_user_func_array([$this->_loaded[$behavior], $callMethod], $args);
<ide> }
<ide>
<ide> public function callFinder($type, array $args = [])
<ide>
<ide> if ($this->hasFinder($type) && $this->has($this->_finderMap[$type][0])) {
<ide> list($behavior, $callMethod) = $this->_finderMap[$type];
<add>
<ide> return call_user_func_array([$this->_loaded[$behavior], $callMethod], $args);
<ide> }
<ide>
<ide><path>src/ORM/EagerLoadable.php
<ide> public function asContainArray()
<ide> if ($this->_forMatching !== null) {
<ide> $config = ['matching' => $this->_forMatching] + $config;
<ide> }
<add>
<ide> return [
<ide> $this->_name => [
<ide> 'associations' => $associations,
<ide><path>src/ORM/EagerLoader.php
<ide> public function contain($associations = [])
<ide> $this->_normalized = null;
<ide> $this->_loadExternal = [];
<ide> $this->_aliasList = [];
<add>
<ide> return $this->_containments = $associations;
<ide> }
<ide>
<ide> public function autoFields($value = null)
<ide> if ($value !== null) {
<ide> $this->_autoFields = (bool)$value;
<ide> }
<add>
<ide> return $this->_autoFields;
<ide> }
<ide>
<ide> public function matching($assoc = null, callable $builder = null, $options = [])
<ide> }
<ide>
<ide> $pointer[$last] = ['queryBuilder' => $builder, 'matching' => true] + $options;
<add>
<ide> return $this->_matching->contain($containments);
<ide> }
<ide>
<ide> public function attachableAssociations(Table $repository)
<ide> $matching = $this->_matching ? $this->_matching->normalized($repository) : [];
<ide> $this->_fixStrategies();
<ide> $this->_loadExternal = [];
<add>
<ide> return $this->_resolveJoins($contain, $matching);
<ide> }
<ide>
<ide> public function externalAssociations(Table $repository)
<ide> }
<ide>
<ide> $this->attachableAssociations($repository);
<add>
<ide> return $this->_loadExternal;
<ide> }
<ide>
<ide> protected function _resolveJoins($associations, $matching = [])
<ide> $loadable->canBeJoined(false);
<ide> $this->_loadExternal[] = $loadable;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function loadExternal($query, $statement)
<ide> );
<ide> $statement = new CallbackStatement($statement, $driver, $f);
<ide> }
<add>
<ide> return $statement;
<ide> }
<ide>
<ide> public function associationsMap($table)
<ide> $visitor($this->_matching->normalized($table), true);
<ide> $visitor($this->normalized($table));
<ide> $visitor($this->_joinsMap);
<add>
<ide> return $map;
<ide> }
<ide>
<ide> protected function _groupKeys($statement, $collectKeys)
<ide> }
<ide>
<ide> $statement->rewind();
<add>
<ide> return $keys;
<ide> }
<ide> }
<ide><path>src/ORM/Entity.php
<ide> public function __construct(array $properties = [], array $options = [])
<ide>
<ide> if (!empty($properties) && $options['markClean'] && !$options['useSetters']) {
<ide> $this->_properties = $properties;
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/ORM/LazyEagerLoader.php
<ide> public function loadInto($entities, array $contain, Table $source)
<ide> $associations = array_keys($query->contain());
<ide>
<ide> $entities = $this->_injectResults($entities, $query, $associations, $source);
<add>
<ide> return $returnSingle ? array_shift($entities) : $entities;
<ide> }
<ide>
<ide> protected function _getQuery($objects, $contain, $source)
<ide>
<ide> $types = array_intersect_key($q->defaultTypes(), array_flip($primaryKey));
<ide> $primaryKey = array_map([$source, 'aliasField'], $primaryKey);
<add>
<ide> return new TupleComparison($primaryKey, $keys->toList(), $types, 'IN');
<ide> })
<ide> ->contain($contain);
<ide> protected function _getPropertyMap($source, $associations)
<ide> foreach ($associations as $assoc) {
<ide> $map[$assoc] = $container->get($assoc)->property();
<ide> }
<add>
<ide> return $map;
<ide> }
<ide>
<ide><path>src/ORM/Locator/LocatorAwareTrait.php
<ide> public function tableLocator(LocatorInterface $tableLocator = null)
<ide> if (!$this->_tableLocator) {
<ide> $this->_tableLocator = TableRegistry::locator();
<ide> }
<add>
<ide> return $this->_tableLocator;
<ide> }
<ide> }
<ide><path>src/ORM/Locator/TableLocator.php
<ide> public function config($alias = null, $options = null)
<ide> $alias
<ide> ));
<ide> }
<add>
<ide> return $this->_config[$alias] = $options;
<ide> }
<ide>
<ide> public function get($alias, array $options = [])
<ide> $alias
<ide> ));
<ide> }
<add>
<ide> return $this->_instances[$alias];
<ide> }
<ide>
<ide> protected function _getClassName($alias, array $options = [])
<ide> if (empty($options['className'])) {
<ide> $options['className'] = Inflector::camelize($alias);
<ide> }
<add>
<ide> return App::className($options['className'], 'Model/Table', 'Table');
<ide> }
<ide>
<ide><path>src/ORM/Marshaller.php
<ide> protected function _buildPropertyMap($options)
<ide> $map[$assoc->property()] = ['association' => $assoc] + $nested + ['associated' => []];
<ide> }
<ide> }
<add>
<ide> return $map;
<ide> }
<ide>
<ide> public function one(array $data, array $options = [])
<ide> if (!isset($options['fieldList'])) {
<ide> $entity->set($properties);
<ide> $entity->errors($errors);
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> public function one(array $data, array $options = [])
<ide> }
<ide>
<ide> $entity->errors($errors);
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> protected function _marshalAssociation($assoc, $value, $options)
<ide> if ($assoc->type() === Association::MANY_TO_MANY) {
<ide> return $marshaller->_belongsToMany($assoc, $value, (array)$options);
<ide> }
<add>
<ide> return $marshaller->many($value, (array)$options);
<ide> }
<ide>
<ide> public function many(array $data, array $options = [])
<ide> }
<ide> $output[] = $this->one($record, $options);
<ide> }
<add>
<ide> return $output;
<ide> }
<ide>
<ide> protected function _belongsToMany(Association $assoc, array $data, $options = []
<ide> $record->set('_joinData', $joinData);
<ide> }
<ide> }
<add>
<ide> return $records;
<ide> }
<ide>
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> $entity->dirty($field, $properties[$field]->dirty());
<ide> }
<ide> }
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> }
<ide>
<ide> $entity->errors($errors);
<add>
<ide> return $entity;
<ide> }
<ide>
<ide> public function mergeMany($entities, array $data, array $options = [])
<ide> foreach ($primary as $key) {
<ide> $keys[] = isset($el[$key]) ? $el[$key] : '';
<ide> }
<add>
<ide> return implode(';', $keys);
<ide> })
<ide> ->map(function ($element, $key) {
<ide> public function mergeMany($entities, array $data, array $options = [])
<ide> })
<ide> ->reduce(function ($query, $keys) use ($primary) {
<ide> $fields = array_map([$this->_table, 'aliasField'], $primary);
<add>
<ide> return $query->orWhere($query->newExpr()->and_(array_combine($fields, $keys)));
<ide> }, $this->_table->find());
<ide>
<ide> protected function _mergeAssociation($original, $assoc, $value, $options)
<ide> if ($assoc->type() === Association::MANY_TO_MANY) {
<ide> return $marshaller->_mergeBelongsToMany($original, $assoc, $value, (array)$options);
<ide> }
<add>
<ide> return $marshaller->mergeMany($original, $value, (array)$options);
<ide> }
<ide>
<ide><path>src/ORM/Query.php
<ide> public function eagerLoader(EagerLoader $instance = null)
<ide> if ($this->_eagerLoader === null) {
<ide> $this->_eagerLoader = new EagerLoader;
<ide> }
<add>
<ide> return $this->_eagerLoader;
<ide> }
<ide> $this->_eagerLoader = $instance;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function contain($associations = null, $override = false)
<ide>
<ide> $result = $loader->contain($associations);
<ide> $this->_addAssociationsToTypeMap($this->repository(), $this->typeMap(), $result);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function matching($assoc, callable $builder = null)
<ide> {
<ide> $this->eagerLoader()->matching($assoc, $builder);
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function leftJoinWith($assoc, callable $builder = null)
<ide> 'fields' => false
<ide> ]);
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function innerJoinWith($assoc, callable $builder = null)
<ide> 'fields' => false
<ide> ]);
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function notMatching($assoc, callable $builder = null)
<ide> 'negateMatch' => true
<ide> ]);
<ide> $this->_dirty();
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function cleanCopy()
<ide> $clone->formatResults(null, true);
<ide> $clone->selectTypeMap(new TypeMap());
<ide> $clone->decorateResults(null, true);
<add>
<ide> return $clone;
<ide> }
<ide>
<ide> protected function _performCount()
<ide> $counter = $this->_counter;
<ide> if ($counter) {
<ide> $query->counter(null);
<add>
<ide> return (int)$counter($query);
<ide> }
<ide>
<ide> protected function _performCount()
<ide>
<ide> $result = $statement->fetch('assoc')['count'];
<ide> $statement->closeCursor();
<add>
<ide> return (int)$result;
<ide> }
<ide>
<ide> protected function _performCount()
<ide> public function counter($counter)
<ide> {
<ide> $this->_counter = $counter;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function hydrate($enable = null)
<ide>
<ide> $this->_dirty();
<ide> $this->_hydrate = (bool)$enable;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function cache($key, $config = 'default')
<ide> if ($this->_type !== 'select' && $this->_type !== null) {
<ide> throw new RuntimeException('You cannot cache the results of non-select queries.');
<ide> }
<add>
<ide> return $this->_cache($key, $config);
<ide> }
<ide>
<ide> public function all()
<ide> 'You cannot call all() on a non-select query. Use execute() instead.'
<ide> );
<ide> }
<add>
<ide> return $this->_all();
<ide> }
<ide>
<ide> public function sql(ValueBinder $binder = null)
<ide>
<ide> $this->_transformQuery();
<ide> $sql = parent::sql($binder);
<add>
<ide> return $sql;
<ide> }
<ide>
<ide> protected function _execute()
<ide> $this->triggerBeforeFind();
<ide> if ($this->_results) {
<ide> $decorator = $this->_decoratorClass();
<add>
<ide> return new $decorator($this->_results);
<ide> }
<ide>
<ide> $statement = $this->eagerLoader()->loadExternal($this, $this->execute());
<add>
<ide> return new ResultSet($this, $statement);
<ide> }
<ide>
<ide> protected function _dirty()
<ide> public function update($table = null)
<ide> {
<ide> $table = $table ?: $this->repository()->table();
<add>
<ide> return parent::update($table);
<ide> }
<ide>
<ide> public function delete($table = null)
<ide> {
<ide> $repo = $this->repository();
<ide> $this->from([$repo->alias() => $repo->table()]);
<add>
<ide> return parent::delete();
<ide> }
<ide>
<ide> public function insert(array $columns, array $types = [])
<ide> {
<ide> $table = $this->repository()->table();
<ide> $this->into($table);
<add>
<ide> return parent::insert($columns, $types);
<ide> }
<ide>
<ide> public function __call($method, $arguments)
<ide> public function __debugInfo()
<ide> {
<ide> $eagerLoader = $this->eagerLoader();
<add>
<ide> return parent::__debugInfo() + [
<ide> 'hydrate' => $this->_hydrate,
<ide> 'buffered' => $this->_useBufferedResults,
<ide> public function autoFields($value = null)
<ide> return $this->_autoFields;
<ide> }
<ide> $this->_autoFields = (bool)$value;
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/ORM/ResultSet.php
<ide> public function valid()
<ide> $valid = $this->_index < $this->_count;
<ide> if ($valid && $this->_results[$this->_index] !== null) {
<ide> $this->_current = $this->_results[$this->_index];
<add>
<ide> return true;
<ide> }
<ide> if (!$valid) {
<ide> public function first()
<ide> if ($this->_statement && !$this->_useBuffering) {
<ide> $this->_statement->closeCursor();
<ide> }
<add>
<ide> return $result;
<ide> }
<ide> }
<ide> public function serialize()
<ide> while ($this->valid()) {
<ide> $this->next();
<ide> }
<add>
<ide> return serialize($this->_results);
<ide> }
<ide>
<ide> public function count()
<ide> if ($this->_statement) {
<ide> return $this->_count = $this->_statement->rowCount();
<ide> }
<add>
<ide> return $this->_count = count($this->_results);
<ide> }
<ide>
<ide> protected function _fetchResult()
<ide> if ($row === false) {
<ide> return $row;
<ide> }
<add>
<ide> return $this->_groupResult($row);
<ide> }
<ide>
<ide><path>src/ORM/Rule/ExistsIn.php
<ide> public function __invoke(EntityInterface $entity, array $options)
<ide> $primary,
<ide> $entity->extract($this->_fields)
<ide> );
<add>
<ide> return $target->exists($conditions);
<ide> }
<ide>
<ide> protected function _fieldsAreNull($entity, $source)
<ide> $nulls++;
<ide> }
<ide> }
<add>
<ide> return $nulls === count($this->_fields);
<ide> }
<ide> }
<ide><path>src/ORM/Rule/IsUnique.php
<ide> protected function _alias($alias, $conditions)
<ide> foreach ($conditions as $key => $value) {
<ide> $aliased["$alias.$key"] = $value;
<ide> }
<add>
<ide> return $aliased;
<ide> }
<ide> }
<ide><path>src/ORM/RulesChecker.php
<ide> public function isUnique(array $fields, $message = null)
<ide> }
<ide>
<ide> $errorField = current($fields);
<add>
<ide> return $this->_addError(new IsUnique($fields), '_isUnique', compact('errorField', 'message'));
<ide> }
<ide>
<ide> public function existsIn($field, $table, $message = null)
<ide> }
<ide>
<ide> $errorField = is_string($field) ? $field : current($field);
<add>
<ide> return $this->_addError(new ExistsIn($field, $table), '_existsIn', compact('errorField', 'message'));
<ide> }
<ide>
<ide> public function validCount($field, $count = 0, $operator = '>', $message = null)
<ide> }
<ide>
<ide> $errorField = $field;
<add>
<ide> return $this->_addError(new ValidCount($field, $count, $operator), '_validCount', compact('count', 'operator', 'errorField', 'message'));
<ide> }
<ide> }
<ide><path>src/ORM/Table.php
<ide> public function table($table = null)
<ide> }
<ide> $this->_table = Inflector::underscore($table);
<ide> }
<add>
<ide> return $this->_table;
<ide> }
<ide>
<ide> public function alias($alias = null)
<ide> $alias = substr(end($alias), 0, -5) ?: $this->_table;
<ide> $this->_alias = $alias;
<ide> }
<add>
<ide> return $this->_alias;
<ide> }
<ide>
<ide> public function registryAlias($registryAlias = null)
<ide> if ($this->_registryAlias === null) {
<ide> $this->_registryAlias = $this->alias();
<ide> }
<add>
<ide> return $this->_registryAlias;
<ide> }
<ide>
<ide> public function schema($schema = null)
<ide> ->describe($this->table())
<ide> );
<ide> }
<add>
<ide> return $this->_schema;
<ide> }
<ide>
<ide> protected function _initializeSchema(Schema $table)
<ide> public function hasField($field)
<ide> {
<ide> $schema = $this->schema();
<add>
<ide> return $schema->column($field) !== null;
<ide> }
<ide>
<ide> public function primaryKey($key = null)
<ide> }
<ide> $this->_primaryKey = $key;
<ide> }
<add>
<ide> return $this->_primaryKey;
<ide> }
<ide>
<ide> public function displayField($key = null)
<ide> $this->_displayField = 'name';
<ide> }
<ide> }
<add>
<ide> return $this->_displayField;
<ide> }
<ide>
<ide> public function belongsTo($associated, array $options = [])
<ide> {
<ide> $options += ['sourceTable' => $this];
<ide> $association = new BelongsTo($associated, $options);
<add>
<ide> return $this->_associations->add($association->name(), $association);
<ide> }
<ide>
<ide> public function hasOne($associated, array $options = [])
<ide> {
<ide> $options += ['sourceTable' => $this];
<ide> $association = new HasOne($associated, $options);
<add>
<ide> return $this->_associations->add($association->name(), $association);
<ide> }
<ide>
<ide> public function hasMany($associated, array $options = [])
<ide> {
<ide> $options += ['sourceTable' => $this];
<ide> $association = new HasMany($associated, $options);
<add>
<ide> return $this->_associations->add($association->name(), $association);
<ide> }
<ide>
<ide> public function belongsToMany($associated, array $options = [])
<ide> {
<ide> $options += ['sourceTable' => $this];
<ide> $association = new BelongsToMany($associated, $options);
<add>
<ide> return $this->_associations->add($association->name(), $association);
<ide> }
<ide>
<ide> public function find($type = 'all', $options = [])
<ide> {
<ide> $query = $this->query();
<ide> $query->select();
<add>
<ide> return $this->callFinder($type, $query, $options);
<ide> }
<ide>
<ide> protected function _setFieldMatchers($options, $keys)
<ide> foreach ($fields as $field) {
<ide> $matches[] = $row[$field];
<ide> }
<add>
<ide> return implode(';', $matches);
<ide> };
<ide> }
<ide> public function get($primaryKey, $options = [])
<ide> }
<ide> $query->cache($cacheKey, $cacheConfig);
<ide> }
<add>
<ide> return $query->firstOrFail();
<ide> }
<ide>
<ide> public function findOrCreate($search, callable $callback = null, $options = [])
<ide> return $this->_processFindOrCreate($search, $callback, $options);
<ide> });
<ide> }
<add>
<ide> return $this->_processFindOrCreate($search, $callback, $options);
<ide> }
<ide>
<ide> protected function _processFindOrCreate($search, callable $callback = null, $opt
<ide> $entity = $callback($entity) ?: $entity;
<ide> }
<ide> unset($options['defaults']);
<add>
<ide> return $this->save($entity, $options) ?: $entity;
<ide> }
<ide>
<ide> public function updateAll($fields, $conditions)
<ide> ->where($conditions);
<ide> $statement = $query->execute();
<ide> $statement->closeCursor();
<add>
<ide> return $statement->rowCount();
<ide> }
<ide>
<ide> public function deleteAll($conditions)
<ide> ->where($conditions);
<ide> $statement = $query->execute();
<ide> $statement->closeCursor();
<add>
<ide> return $statement->rowCount();
<ide> }
<ide>
<ide> protected function _processSave($entity, $options)
<ide> if ($success) {
<ide> return $entity;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _insert($entity, $data)
<ide> }
<ide> }
<ide> $statement->closeCursor();
<add>
<ide> return $success;
<ide> }
<ide>
<ide> protected function _newId($primary)
<ide> }
<ide> $typeName = $this->schema()->columnType($primary[0]);
<ide> $type = Type::build($typeName);
<add>
<ide> return $type->newId();
<ide> }
<ide>
<ide> protected function _update($entity, $data)
<ide> $success = $entity;
<ide> }
<ide> $statement->closeCursor();
<add>
<ide> return $success;
<ide> }
<ide>
<ide> function () use ($entities, $options, &$isNew) {
<ide> $entity->isNew(true);
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function delete(EntityInterface $entity, $options = [])
<ide> 'options' => $options
<ide> ]);
<ide> }
<add>
<ide> return $success;
<ide> }
<ide>
<ide> protected function _dynamicFinder($method, $args)
<ide> foreach ($fields as $field) {
<ide> $conditions[$this->aliasField($field)] = array_shift($args);
<ide> }
<add>
<ide> return $conditions;
<ide> };
<ide>
<ide> public function __get($property)
<ide> $property
<ide> ));
<ide> }
<add>
<ide> return $association;
<ide> }
<ide>
<ide> public function newEntity($data = null, array $options = [])
<ide> if ($data === null) {
<ide> $class = $this->entityClass();
<ide> $entity = new $class([], ['source' => $this->registryAlias()]);
<add>
<ide> return $entity;
<ide> }
<ide> if (!isset($options['associated'])) {
<ide> $options['associated'] = $this->_associations->keys();
<ide> }
<ide> $marshaller = $this->marshaller();
<add>
<ide> return $marshaller->one($data, $options);
<ide> }
<ide>
<ide> public function newEntities(array $data, array $options = [])
<ide> $options['associated'] = $this->_associations->keys();
<ide> }
<ide> $marshaller = $this->marshaller();
<add>
<ide> return $marshaller->many($data, $options);
<ide> }
<ide>
<ide> public function patchEntity(EntityInterface $entity, array $data, array $options
<ide> $options['associated'] = $this->_associations->keys();
<ide> }
<ide> $marshaller = $this->marshaller();
<add>
<ide> return $marshaller->merge($entity, $data, $options);
<ide> }
<ide>
<ide> public function patchEntities($entities, array $data, array $options = [])
<ide> $options['associated'] = $this->_associations->keys();
<ide> }
<ide> $marshaller = $this->marshaller();
<add>
<ide> return $marshaller->mergeMany($entities, $data, $options);
<ide> }
<ide>
<ide> public function validateUnique($value, array $options, array $context = null)
<ide> isset($options['scope']) ? (array)$options['scope'] : []
<ide> );
<ide> $rule = new IsUnique($fields);
<add>
<ide> return $rule($entity, ['repository' => $this]);
<ide> }
<ide>
<ide> public function implementedEvents()
<ide> }
<ide> $events[$event] = $method;
<ide> }
<add>
<ide> return $events;
<ide> }
<ide>
<ide> public function __debugInfo()
<ide> $conn = $this->connection();
<ide> $associations = $this->_associations ?: false;
<ide> $behaviors = $this->_behaviors ?: false;
<add>
<ide> return [
<ide> 'registryAlias' => $this->registryAlias(),
<ide> 'table' => $this->table(),
<ide><path>src/Routing/Dispatcher.php
<ide> public function dispatch(Request $request, Response $response)
<ide> return $beforeEvent->result->body();
<ide> }
<ide> $beforeEvent->result->send();
<add>
<ide> return null;
<ide> }
<ide>
<ide><path>src/Routing/DispatcherFactory.php
<ide> public static function add($filter, array $options = [])
<ide> $filter = static::_createFilter($filter, $options);
<ide> }
<ide> static::$_stack[] = $filter;
<add>
<ide> return $filter;
<ide> }
<ide>
<ide> protected static function _createFilter($name, $options)
<ide> $msg = sprintf('Cannot locate dispatcher filter named "%s".', $name);
<ide> throw new MissingDispatcherFilterException($msg);
<ide> }
<add>
<ide> return new $className($options);
<ide> }
<ide>
<ide> public static function create()
<ide> foreach (static::$_stack as $middleware) {
<ide> $dispatcher->addFilter($middleware);
<ide> }
<add>
<ide> return $dispatcher;
<ide> }
<ide>
<ide><path>src/Routing/DispatcherFilter.php
<ide> public function matches(Event $event)
<ide> $response = $event->data['response'];
<ide> $pass = $this->_config['when']($request, $response);
<ide> }
<add>
<ide> return $pass;
<ide> }
<ide>
<ide><path>src/Routing/Filter/AssetFilter.php
<ide> public function beforeDispatch(Event $event)
<ide> $pathSegments = explode('.', $url);
<ide> $ext = array_pop($pathSegments);
<ide> $this->_deliverAsset($request, $response, $assetFile, $ext);
<add>
<ide> return $response;
<ide> }
<ide>
<ide> protected function _getAssetFile($url)
<ide> $parts = array_slice($parts, $i + 1);
<ide> $fileFragment = implode(DIRECTORY_SEPARATOR, $parts);
<ide> $pluginWebroot = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR;
<add>
<ide> return $pluginWebroot . $fileFragment;
<ide> }
<ide> }
<ide><path>src/Routing/Filter/ControllerFactoryFilter.php
<ide> protected function _getController($request, $response)
<ide> if ($reflection->isAbstract() || $reflection->isInterface()) {
<ide> return false;
<ide> }
<add>
<ide> return $reflection->newInstance($request, $response, $controller);
<ide> }
<ide> }
<ide><path>src/Routing/Filter/RoutingFilter.php
<ide> public function beforeDispatch(Event $event)
<ide> $response = $event->data['response'];
<ide> $response->statusCode($e->getCode());
<ide> $response->header('Location', $e->getMessage());
<add>
<ide> return $response;
<ide> }
<ide> }
<ide><path>src/Routing/RequestActionTrait.php
<ide> public function requestAction($url, array $extra = [])
<ide> $dispatcher = DispatcherFactory::create();
<ide> $result = $dispatcher->dispatch($request, new Response());
<ide> Router::popRequest();
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>src/Routing/Route/DashedRoute.php
<ide> protected function _camelizePlugin($plugin)
<ide> return Inflector::camelize($plugin);
<ide> }
<ide> list($vendor, $plugin) = explode('/', $plugin, 2);
<add>
<ide> return Inflector::camelize($vendor) . '/' . Inflector::camelize($plugin);
<ide> }
<ide>
<ide> public function parse($url)
<ide> $params['action']
<ide> ));
<ide> }
<add>
<ide> return $params;
<ide> }
<ide>
<ide> public function match(array $url, array $context = [])
<ide> $this->_inflectedDefaults = true;
<ide> $this->defaults = $this->_dasherize($this->defaults);
<ide> }
<add>
<ide> return parent::match($url, $context);
<ide> }
<ide>
<ide> protected function _dasherize($url)
<ide> $url[$element] = Inflector::dasherize($url[$element]);
<ide> }
<ide> }
<add>
<ide> return $url;
<ide> }
<ide> }
<ide><path>src/Routing/Route/InflectedRoute.php
<ide> public function parse($url)
<ide> $params['plugin'] = Inflector::camelize($vendor) . '/' . Inflector::camelize($plugin);
<ide> }
<ide> }
<add>
<ide> return $params;
<ide> }
<ide>
<ide> public function match(array $url, array $context = [])
<ide> $this->_inflectedDefaults = true;
<ide> $this->defaults = $this->_underscore($this->defaults);
<ide> }
<add>
<ide> return parent::match($url, $context);
<ide> }
<ide>
<ide> protected function _underscore($url)
<ide> if (!empty($url['plugin'])) {
<ide> $url['plugin'] = Inflector::underscore($url['plugin']);
<ide> }
<add>
<ide> return $url;
<ide> }
<ide> }
<ide><path>src/Routing/Route/PluginShortRoute.php
<ide> public function parse($url)
<ide> return false;
<ide> }
<ide> $params['controller'] = $params['plugin'];
<add>
<ide> return $params;
<ide> }
<ide>
<ide> public function match(array $url, array $context = [])
<ide> $this->defaults['controller'] = $url['controller'];
<ide> $result = parent::match($url, $context);
<ide> unset($this->defaults['controller']);
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>src/Routing/Route/Route.php
<ide> public function compile()
<ide> return $this->_compiledRoute;
<ide> }
<ide> $this->_writeRoute();
<add>
<ide> return $this->_compiledRoute;
<ide> }
<ide>
<ide> protected function _writeRoute()
<ide> if (empty($this->template) || ($this->template === '/')) {
<ide> $this->_compiledRoute = '#^/*$#';
<ide> $this->keys = [];
<add>
<ide> return;
<ide> }
<ide> $route = $this->template;
<ide> public function getName()
<ide> }
<ide> $name .= $value . $glue;
<ide> }
<add>
<ide> return $this->_name = strtolower($name);
<ide> }
<ide>
<ide> public function parse($url)
<ide> }
<ide>
<ide> $route['_matchedRoute'] = $this->template;
<add>
<ide> return $route;
<ide> }
<ide>
<ide> protected function _parseExtension($url)
<ide> foreach ($this->_extensions as $name) {
<ide> if (strtolower($name) === $ext) {
<ide> $url = substr($url, 0, ($len + 1) * -1);
<add>
<ide> return [$url, $ext];
<ide> }
<ide> }
<add>
<ide> return [$url, null];
<ide> }
<ide>
<ide> protected function _parseArgs($args, $context)
<ide> }
<ide> $pass[] = rawurldecode($param);
<ide> }
<add>
<ide> return $pass;
<ide> }
<ide>
<ide> protected function _persistParams(array $url, array $params)
<ide> $url[$persistKey] = $params[$persistKey];
<ide> }
<ide> }
<add>
<ide> return $url;
<ide> }
<ide>
<ide> public function match(array $url, array $context = [])
<ide> }
<ide> }
<ide> $url += $hostOptions;
<add>
<ide> return $this->_writeUrl($url, $pass, $query);
<ide> }
<ide>
<ide> protected function _matchMethod($url)
<ide> if (!in_array(strtoupper($url['_method']), (array)$this->defaults['_method'])) {
<ide> return false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _writeUrl($params, $pass = [], $query = [])
<ide> if (!empty($query)) {
<ide> $out .= rtrim('?' . http_build_query($query), '?');
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function staticPath()
<ide> $star = strpos($this->template, '*');
<ide> if ($star !== false) {
<ide> $path = rtrim(substr($this->template, 0, $star), '/');
<add>
<ide> return $path === '' ? '/' : $path;
<ide> }
<add>
<ide> return $this->template;
<ide> }
<ide>
<ide> public static function __set_state($fields)
<ide> foreach ($fields as $field => $value) {
<ide> $obj->$field = $value;
<ide> }
<add>
<ide> return $obj;
<ide> }
<ide> }
<ide><path>src/Routing/RouteBuilder.php
<ide> public function path()
<ide> if ($routeKey !== false) {
<ide> return substr($this->_path, 0, $routeKey);
<ide> }
<add>
<ide> return $this->_path;
<ide> }
<ide>
<ide> public function namePrefix($value = null)
<ide> if ($value !== null) {
<ide> $this->_namePrefix = $value;
<ide> }
<add>
<ide> return $this->_namePrefix;
<ide> }
<ide>
<ide><path>src/Routing/RouteCollection.php
<ide> public function parse($url)
<ide> if ($queryParameters) {
<ide> $r['?'] = $queryParameters;
<ide> }
<add>
<ide> return $r;
<ide> }
<ide> }
<ide><path>src/Routing/Router.php
<ide> public static function mapResources($controller, $options = [])
<ide> $path = '/' . implode('/', [$prefix, $pluginUrl]);
<ide> $params = ['prefix' => $prefix, 'plugin' => $plugin];
<ide> static::scope($path, $params, $callback);
<add>
<ide> return;
<ide> }
<ide>
<ide> if ($prefix) {
<ide> static::prefix($prefix, $callback);
<add>
<ide> return;
<ide> }
<ide>
<ide> if ($plugin) {
<ide> static::plugin($plugin, $callback);
<add>
<ide> return;
<ide> }
<ide>
<ide> static::scope('/', $callback);
<add>
<ide> return;
<ide> }
<ide> }
<ide> public static function parse($url)
<ide> if (strpos($url, '/') !== 0) {
<ide> $url = '/' . $url;
<ide> }
<add>
<ide> return static::$_collection->parse($url);
<ide> }
<ide>
<ide> public static function popRequest()
<ide> static::_setContext($last);
<ide> reset(static::$_requests);
<ide> }
<add>
<ide> return $removed;
<ide> }
<ide>
<ide> public static function getRequest($current = false)
<ide> if ($current) {
<ide> return end(static::$_requests);
<ide> }
<add>
<ide> return isset(static::$_requests[0]) ? static::$_requests[0] : null;
<ide> }
<ide>
<ide> public static function reload()
<ide> if (empty(static::$_initialState)) {
<ide> static::$_collection = new RouteCollection();
<ide> static::$_initialState = get_class_vars(get_called_class());
<add>
<ide> return;
<ide> }
<ide> foreach (static::$_initialState as $key => $val) {
<ide> protected static function _applyUrlFilters($url)
<ide> foreach (static::$_urlFilters as $filter) {
<ide> $url = $filter($url, $request);
<ide> }
<add>
<ide> return $url;
<ide> }
<ide>
<ide> public static function url($url = null, $full = false)
<ide> if ($full) {
<ide> $output = static::fullBaseUrl() . $output;
<ide> }
<add>
<ide> return $output;
<ide> }
<ide> if (is_array($url)) {
<ide> public static function url($url = null, $full = false)
<ide> $output = static::fullBaseUrl() . $output;
<ide> }
<ide> }
<add>
<ide> return $output . $frag;
<ide> }
<ide>
<ide> public static function fullBaseUrl($base = null)
<ide> if (empty(static::$_fullBaseUrl)) {
<ide> static::$_fullBaseUrl = Configure::read('App.fullBaseUrl');
<ide> }
<add>
<ide> return static::$_fullBaseUrl;
<ide> }
<ide>
<ide> public static function reverse($params, $full = false)
<ide> if (!empty($url)) {
<ide> $params['?'] = $url;
<ide> }
<add>
<ide> return Router::url($params, $full);
<ide> }
<ide>
<ide> public static function normalize($url = '/')
<ide> if (empty($url)) {
<ide> return '/';
<ide> }
<add>
<ide> return $url;
<ide> }
<ide>
<ide> public static function extensions($extensions = null, $merge = true)
<ide> if (!static::$initialized) {
<ide> static::_loadRoutes();
<ide> }
<add>
<ide> return array_unique(array_merge(static::$_defaultExtensions, $collection->extensions()));
<ide> }
<ide> $extensions = (array)$extensions;
<ide> if ($merge) {
<ide> $extensions = array_unique(array_merge(static::$_defaultExtensions, $extensions));
<ide> }
<add>
<ide> return static::$_defaultExtensions = $extensions;
<ide> }
<ide>
<ide> public static function parseNamedParams(Request $request, array $options = [])
<ide> $options += ['separator' => ':'];
<ide> if (empty($request->params['pass'])) {
<ide> $request->params['named'] = [];
<add>
<ide> return $request;
<ide> }
<ide> $named = [];
<ide> public static function parseNamedParams(Request $request, array $options = [])
<ide> $named = array_merge_recursive($named, [$key => $value]);
<ide> }
<ide> $request->params['named'] = $named;
<add>
<ide> return $request;
<ide> }
<ide>
<ide> public static function routes()
<ide> if (!static::$initialized) {
<ide> static::_loadRoutes();
<ide> }
<add>
<ide> return static::$_collection->routes();
<ide> }
<ide>
<ide><path>src/Shell/CommandListShell.php
<ide> public function main()
<ide>
<ide> if ($this->param('version')) {
<ide> $this->out(Configure::version());
<add>
<ide> return;
<ide> }
<ide>
<ide><path>src/Shell/CompletionShell.php
<ide> public function main()
<ide> public function commands()
<ide> {
<ide> $options = $this->Command->commands();
<add>
<ide> return $this->_output($options);
<ide> }
<ide>
<ide> public function subcommands()
<ide> }
<ide>
<ide> $options = $this->Command->subCommands($this->args[0]);
<add>
<ide> return $this->_output($options);
<ide> }
<ide>
<ide><path>src/Shell/Helper/TableHelper.php
<ide> protected function _calculateWidths($rows)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $widths;
<ide> }
<ide>
<ide><path>src/Shell/I18nShell.php
<ide> public function main()
<ide> break;
<ide> case 'q':
<ide> $this->_stop();
<add>
<ide> return;
<ide> default:
<ide> $this->out('You have made an invalid selection. Please choose a command to execute by entering E, I, H, or Q.');
<ide><path>src/Shell/OrmCacheShell.php
<ide> public function build($name = null)
<ide> $schema->describe($table, ['forceRefresh' => true]);
<ide> }
<ide> $this->out('<success>Cache build complete</success>');
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function clear($name = null)
<ide> Cache::delete($key, $configName);
<ide> }
<ide> $this->out('<success>Cache clear complete</success>');
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _getSchema()
<ide> $this->params['connection']
<ide> );
<ide> $this->error($msg);
<add>
<ide> return false;
<ide> }
<ide> $config = $source->config();
<ide> if (empty($config['cacheMetadata'])) {
<ide> $this->_io->verbose('Metadata cache was disabled in config. Enabling to clear cache.');
<ide> $source->cacheMetadata(true);
<ide> }
<add>
<ide> return $source->schemaCollection();
<ide> }
<ide>
<ide><path>src/Shell/RoutesShell.php
<ide> public function check($url)
<ide> } catch (MissingRouteException $e) {
<ide> $this->err("<warning>'$url' did not match any routes.</warning>");
<ide> $this->out();
<add>
<ide> return false;
<ide> }
<ide> }
<ide> public function generate()
<ide> } catch (MissingRouteException $e) {
<ide> $this->err("<warning>The provided parameters do not match any routes.</warning>");
<ide> $this->out();
<add>
<ide> return false;
<ide> }
<ide> }
<ide> public function getOptionParser()
<ide> "Routing parameters should be supplied in a key:value format. " .
<ide> "For example `controller:Articles action:view 2`"
<ide> ]);
<add>
<ide> return $parser;
<ide> }
<ide>
<ide> protected function _splitArgs($args)
<ide> $out[] = $arg;
<ide> }
<ide> }
<add>
<ide> return $out;
<ide> }
<ide> }
<ide><path>src/Shell/Task/AssetsTask.php
<ide> protected function _list($name = null)
<ide> } else {
<ide> if (!Plugin::loaded($name)) {
<ide> $this->err(sprintf('Plugin %s is not loaded.', $name));
<add>
<ide> return [];
<ide> }
<ide> $pluginsList = [$name];
<ide> protected function _createDirectory($dir)
<ide>
<ide> if ($result) {
<ide> $this->out('Created directory ' . $dir);
<add>
<ide> return true;
<ide> }
<ide>
<ide> $this->err('Failed creating directory ' . $dir);
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _createSymlink($target, $link)
<ide>
<ide> if ($result) {
<ide> $this->out('Created symlink ' . $link);
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _copyDirectory($source, $destination)
<ide> $folder = new Folder($source);
<ide> if ($folder->copy(['to' => $destination])) {
<ide> $this->out('Copied assets to directory ' . $destination);
<add>
<ide> return true;
<ide> }
<ide>
<ide> $this->err('Error copying assets to directory ' . $destination);
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Shell/Task/CommandTask.php
<ide> protected function _appendShells($type, $shells, $shellList)
<ide> foreach ($shells as $shell) {
<ide> $shellList[$type][] = Inflector::underscore(str_replace('Shell', '', $shell));
<ide> }
<add>
<ide> return $shellList;
<ide> }
<ide>
<ide> protected function _scanDir($dir)
<ide> }
<ide> $shells[] = substr($file, 0, -4);
<ide> }
<add>
<ide> return $shells;
<ide> }
<ide>
<ide> public function options($commandName, $subCommandName = '')
<ide> $options[] = "-$short";
<ide> }
<ide> }
<add>
<ide> return $options;
<ide> }
<ide> }
<ide><path>src/Shell/Task/ExtractTask.php
<ide> protected function _getPaths()
<ide> if (strtoupper($response) === 'Q') {
<ide> $this->err('Extract Aborted');
<ide> $this->_stop();
<add>
<ide> return;
<ide> }
<ide> if (strtoupper($response) === 'D' && count($this->_paths)) {
<ide> $this->out();
<add>
<ide> return;
<ide> }
<ide> if (strtoupper($response) === 'D') {
<ide> public function main()
<ide> if (strtoupper($response) === 'Q') {
<ide> $this->err('Extract Aborted');
<ide> $this->_stop();
<add>
<ide> return;
<ide> }
<ide> if ($this->_isPathUsable($response)) {
<ide> public function main()
<ide> if (!$this->_isPathUsable($this->_output)) {
<ide> $this->err(sprintf('The output directory %s was not found or writable.', $this->_output));
<ide> $this->_stop();
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _writeHeader()
<ide> $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
<ide> $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
<ide> $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
<add>
<ide> return $output;
<ide> }
<ide>
<ide> protected function _getStrings(&$position, $target)
<ide> }
<ide> $position++;
<ide> }
<add>
<ide> return $strings;
<ide> }
<ide>
<ide> protected function _formatString($string)
<ide> $string = strtr($string, ["\\'" => "'", "\\\\" => "\\"]);
<ide> }
<ide> $string = str_replace("\r\n", "\n", $string);
<add>
<ide> return addcslashes($string, "\0..\37\\\"");
<ide> }
<ide>
<ide> protected function _isPathUsable($path)
<ide> if (!is_dir($path)) {
<ide> mkdir($path, 0770, true);
<ide> }
<add>
<ide> return is_dir($path) && is_writable($path);
<ide> }
<ide> }
<ide><path>src/Shell/Task/LoadTask.php
<ide> public function main($plugin = null)
<ide> if (empty($plugin)) {
<ide> $this->err('<error>You must provide a plugin name in CamelCase format.</error>');
<ide> $this->err('To load an "Example" plugin, run <info>`cake plugin load Example`</info>.');
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _modifyBootstrap($plugin, $hasBootstrap, $hasRoutes, $hasAuto
<ide> $bootstrap->append(str_replace(', []', '', sprintf($append, $plugin, $options)));
<ide> $this->out('');
<ide> $this->out(sprintf('%s modified', $this->bootstrap));
<add>
<ide> return true;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Shell/Task/UnloadTask.php
<ide> public function main($plugin = null)
<ide> if (empty($plugin)) {
<ide> $this->err('<error>You must provide a plugin name in CamelCase format.</error>');
<ide> $this->err('To unload an "Example" plugin, run <info>`cake plugin unload Example`</info>.');
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _modifyBootstrap($plugin)
<ide>
<ide> return true;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> protected function _fixtureConnections($fixtures)
<ide> $dbs[$fixture->connection()][$f] = $fixture;
<ide> }
<ide> }
<add>
<ide> return $dbs;
<ide> }
<ide>
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> public function schema(Table $schema = null)
<ide> {
<ide> if ($schema) {
<ide> $this->_schema = $schema;
<add>
<ide> return null;
<ide> }
<add>
<ide> return $this->_schema;
<ide> }
<ide>
<ide> public function create(ConnectionInterface $db)
<ide> );
<ide> Log::error($msg);
<ide> trigger_error($msg, E_USER_WARNING);
<add>
<ide> return false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function drop(ConnectionInterface $db)
<ide> } catch (Exception $e) {
<ide> return false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function insert(ConnectionInterface $db)
<ide> }
<ide> $statement = $query->execute();
<ide> $statement->closeCursor();
<add>
<ide> return $statement;
<ide> }
<ide>
<ide> public function dropConstraints(ConnectionInterface $db)
<ide> foreach ($this->_constraints as $name => $data) {
<ide> $this->_schema->dropConstraint($name);
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _getRecords()
<ide> foreach ($this->records as $record) {
<ide> $values[] = array_merge($default, $record);
<ide> }
<add>
<ide> return [$fields, $values, $types];
<ide> }
<ide>
<ide> public function truncate(ConnectionInterface $db)
<ide> foreach ($sql as $stmt) {
<ide> $db->execute($stmt)->closeCursor();
<ide> }
<add>
<ide> return true;
<ide> }
<ide> }
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> protected function _getCookieEncryptionKey()
<ide> if (isset($this->_cookieEncriptionKey)) {
<ide> return $this->_cookieEncriptionKey;
<ide> }
<add>
<ide> return Security::salt();
<ide> }
<ide>
<ide> protected function _buildRequest($url, $method, $data)
<ide> $env['REQUEST_METHOD'] = $method;
<ide> $props['environment'] = $env;
<ide> $props = Hash::merge($props, $this->_request);
<add>
<ide> return new Request($props);
<ide> }
<ide>
<ide> protected function _addTokens($url, $data)
<ide> $data['_csrfToken'] = $this->_cookie['csrfToken'];
<ide> }
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public function viewVariable($name)
<ide> if (isset($this->_controller->viewVars[$name])) {
<ide> return $this->_controller->viewVars[$name];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function assertRedirect($url = null, $message = '')
<ide> $result = $this->_response->header();
<ide> if ($url === null) {
<ide> $this->assertTrue(!empty($result['Location']), $message);
<add>
<ide> return;
<ide> }
<ide> if (empty($result['Location'])) {
<ide><path>src/TestSuite/TestCase.php
<ide> public function skipIf($shouldSkip, $message = '')
<ide> if ($shouldSkip) {
<ide> $this->markTestSkipped($message);
<ide> }
<add>
<ide> return $shouldSkip;
<ide> }
<ide>
<ide> public function assertHtml($expected, $string, $fullDebug = false)
<ide> debug($regex);
<ide> }
<ide> $this->assertRegExp($expression, $string, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description));
<add>
<ide> return false;
<ide> }
<ide> }
<ide>
<ide> $this->assertTrue(true, '%s');
<add>
<ide> return true;
<ide> }
<ide>
<ide> protected function _assertAttributes($assertions, $string, $fullDebug = false, $
<ide> }
<ide> $len = count($asserts);
<ide> } while ($len > 0);
<add>
<ide> return $string;
<ide> }
<ide>
<ide> protected function skipUnless($condition, $message = '')
<ide> if (!$condition) {
<ide> $this->markTestSkipped($message);
<ide> }
<add>
<ide> return $condition;
<ide> }
<ide>
<ide> public function getMockForModel($alias, array $methods = [], array $options = []
<ide> }
<ide>
<ide> TableRegistry::set($baseClass, $mock);
<add>
<ide> return $mock;
<ide> }
<ide> }
<ide><path>src/Utility/CookieCryptTrait.php
<ide> protected function _encrypt($value, $encrypt, $key = null)
<ide> if ($encrypt === 'aes') {
<ide> $cipher = Security::encrypt($value, $key);
<ide> }
<add>
<ide> return $prefix . base64_encode($cipher);
<ide> }
<ide>
<ide> protected function _decrypt($values, $mode, $key = null)
<ide> foreach ($values as $name => $value) {
<ide> $decrypted[$name] = $this->_decode($value, $mode, $key);
<ide> }
<add>
<ide> return $decrypted;
<ide> }
<ide>
<ide> protected function _decode($value, $encrypt, $key)
<ide> if ($encrypt === 'aes') {
<ide> $value = Security::decrypt($value, $key);
<ide> }
<add>
<ide> return $this->_explode($value);
<ide> }
<ide>
<ide> protected function _explode($string)
<ide> $first = substr($string, 0, 1);
<ide> if ($first === '{' || $first === '[') {
<ide> $ret = json_decode($string, true);
<add>
<ide> return ($ret !== null) ? $ret : $string;
<ide> }
<ide> $array = [];
<ide> protected function _explode($string)
<ide> }
<ide> $array[$key[0]] = $key[1];
<ide> }
<add>
<ide> return $array;
<ide> }
<ide> }
<ide><path>src/Utility/Crypto/Mcrypt.php
<ide> public static function rijndael($text, $key, $operation)
<ide>
<ide> if ($operation === 'encrypt') {
<ide> $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
<add>
<ide> return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
<ide> }
<ide> $iv = mb_substr($text, 0, $ivSize, '8bit');
<ide> $text = mb_substr($text, $ivSize + 2, null, '8bit');
<add>
<ide> return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
<ide> }
<ide>
<ide> public static function decrypt($cipher, $key)
<ide> }
<ide> $padLen = ord($padChar);
<ide> $result = mb_substr($plain, 0, -$padLen, '8bit');
<add>
<ide> return $result === '' ? false : $result;
<ide> }
<ide> }
<ide><path>src/Utility/Crypto/OpenSsl.php
<ide> public static function encrypt($plain, $key, $hmacSalt = null)
<ide> $ivSize = openssl_cipher_iv_length($method);
<ide>
<ide> $iv = openssl_random_pseudo_bytes($ivSize);
<add>
<ide> return $iv . openssl_encrypt($plain, $method, $key, OPENSSL_RAW_DATA, $iv);
<ide> }
<ide>
<ide> public static function decrypt($cipher, $key)
<ide> $iv = mb_substr($cipher, 0, $ivSize, '8bit');
<ide>
<ide> $cipher = mb_substr($cipher, $ivSize, null, '8bit');
<add>
<ide> return openssl_decrypt($cipher, $method, $key, OPENSSL_RAW_DATA, $iv);
<ide> }
<ide> }
<ide><path>src/Utility/Hash.php
<ide> public static function extract($data, $path)
<ide> }
<ide> $context = [$_key => $next];
<ide> }
<add>
<ide> return $context[$_key];
<ide> }
<ide>
<ide> protected static function _matches($data, $selector)
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function insert(array $data, $path, $values = null)
<ide> $noTokens = strpos($path, '[') === false;
<ide> if ($noTokens && strpos($path, '.') === false) {
<ide> $data[$path] = $values;
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public static function insert(array $data, $path, $values = null)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> protected static function _simpleOp($op, $data, $path, $values = null)
<ide> if ($op === 'insert') {
<ide> if ($i === $last) {
<ide> $_list[$key] = $values;
<add>
<ide> return $data;
<ide> }
<ide> if (!isset($_list[$key])) {
<ide> protected static function _simpleOp($op, $data, $path, $values = null)
<ide> } elseif ($op === 'remove') {
<ide> if ($i === $last) {
<ide> unset($_list[$key]);
<add>
<ide> return $data;
<ide> }
<ide> if (!isset($_list[$key])) {
<ide> public static function remove(array $data, $path)
<ide>
<ide> if ($noExpansion && $noTokens && strpos($path, '.') === false) {
<ide> unset($data[$path]);
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public static function remove(array $data, $path)
<ide> unset($data[$k]);
<ide> }
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> }
<ide> $out[$group[$i]][$keys[$i]] = $vals[$i];
<ide> }
<add>
<ide> return $out;
<ide> }
<ide> }
<ide> if (empty($vals)) {
<ide> return [];
<ide> }
<add>
<ide> return array_combine($keys, $vals);
<ide> }
<ide>
<ide> public static function format(array $data, array $paths, $format)
<ide> }
<ide> $out[] = vsprintf($format, $args);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public static function contains(array $data, array $needle)
<ide> list($needle, $data) = array_pop($stack);
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function check(array $data, $path)
<ide> if (!is_array($results)) {
<ide> return false;
<ide> }
<add>
<ide> return count($results) > 0;
<ide> }
<ide>
<ide> public static function filter(array $data, $callback = ['self', '_filter'])
<ide> $data[$k] = static::filter($v, $callback);
<ide> }
<ide> }
<add>
<ide> return array_filter($data, $callback);
<ide> }
<ide>
<ide> public static function flatten(array $data, $separator = '.')
<ide> reset($data);
<ide> }
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public static function expand(array $data, $separator = '.')
<ide> $stack = [[$child, &$result]];
<ide> static::_merge($stack, $result);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public static function merge(array $data, $merge)
<ide> }
<ide> unset($curArg);
<ide> static::_merge($stack, $return);
<add>
<ide> return $return;
<ide> }
<ide>
<ide> public static function numeric(array $data)
<ide> if (empty($data)) {
<ide> return false;
<ide> }
<add>
<ide> return $data === array_filter($data, 'is_numeric');
<ide> }
<ide>
<ide> public static function dimensions(array $data)
<ide> break;
<ide> }
<ide> }
<add>
<ide> return $depth;
<ide> }
<ide>
<ide> public static function maxDimensions(array $data)
<ide> }
<ide> }
<ide> }
<add>
<ide> return empty($depth) ? 0 : max($depth);
<ide> }
<ide>
<ide> public static function maxDimensions(array $data)
<ide> public static function map(array $data, $path, $function)
<ide> {
<ide> $values = (array)static::extract($data, $path);
<add>
<ide> return array_map($function, $values);
<ide> }
<ide>
<ide> public static function map(array $data, $path, $function)
<ide> public static function reduce(array $data, $path, $function)
<ide> {
<ide> $values = (array)static::extract($data, $path);
<add>
<ide> return array_reduce($values, $function);
<ide> }
<ide>
<ide> public static function reduce(array $data, $path, $function)
<ide> public static function apply(array $data, $path, $function)
<ide> {
<ide> $values = (array)static::extract($data, $path);
<add>
<ide> return call_user_func($function, $values);
<ide> }
<ide>
<ide> public static function sort(array $data, $path, $dir = 'asc', $type = 'regular')
<ide> $sorted[$k] = $data[$k];
<ide> }
<ide> }
<add>
<ide> return $sorted;
<ide> }
<ide>
<ide> protected static function _squash(array $data, $key = null)
<ide> $stack[] = ['id' => $id, 'value' => $r];
<ide> }
<ide> }
<add>
<ide> return $stack;
<ide> }
<ide>
<ide> public static function diff(array $data, array $compare)
<ide> }
<ide> next($intersection);
<ide> }
<add>
<ide> return $data + $compare;
<ide> }
<ide>
<ide> public static function mergeDiff(array $data, array $compare)
<ide> $data[$key] = static::mergeDiff($data[$key], $compare[$key]);
<ide> }
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public static function normalize(array $data, $assoc = true)
<ide> }
<ide> $data = $newList;
<ide> }
<add>
<ide> return $data;
<ide> }
<ide>
<ide> public static function nest(array $data, array $options = [])
<ide> unset($return[$i]);
<ide> }
<ide> }
<add>
<ide> return array_values($return);
<ide> }
<ide> }
<ide><path>src/Utility/Inflector.php
<ide> protected static function _cache($type, $key, $value = false)
<ide> $type = '_' . $type;
<ide> if ($value !== false) {
<ide> static::$_cache[$type][$key] = $value;
<add>
<ide> return $value;
<ide> }
<ide> if (!isset(static::$_cache[$type][$key])) {
<ide> return false;
<ide> }
<add>
<ide> return static::$_cache[$type][$key];
<ide> }
<ide>
<ide> public static function reset()
<ide> {
<ide> if (empty(static::$_initialState)) {
<ide> static::$_initialState = get_class_vars(__CLASS__);
<add>
<ide> return;
<ide> }
<ide> foreach (static::$_initialState as $key => $val) {
<ide> public static function pluralize($word)
<ide> if (preg_match('/(.*?(?:\\b|_))(' . static::$_cache['irregular']['pluralize'] . ')$/i', $word, $regs)) {
<ide> static::$_cache['pluralize'][$word] = $regs[1] . substr($regs[2], 0, 1) .
<ide> substr(static::$_irregular[strtolower($regs[2])], 1);
<add>
<ide> return static::$_cache['pluralize'][$word];
<ide> }
<ide>
<ide> public static function pluralize($word)
<ide>
<ide> if (preg_match('/^(' . static::$_cache['uninflected'] . ')$/i', $word, $regs)) {
<ide> static::$_cache['pluralize'][$word] = $word;
<add>
<ide> return $word;
<ide> }
<ide>
<ide> foreach (static::$_plural as $rule => $replacement) {
<ide> if (preg_match($rule, $word)) {
<ide> static::$_cache['pluralize'][$word] = preg_replace($rule, $replacement, $word);
<add>
<ide> return static::$_cache['pluralize'][$word];
<ide> }
<ide> }
<ide> public static function singularize($word)
<ide> if (preg_match('/(.*?(?:\\b|_))(' . static::$_cache['irregular']['singular'] . ')$/i', $word, $regs)) {
<ide> static::$_cache['singularize'][$word] = $regs[1] . substr($regs[2], 0, 1) .
<ide> substr(array_search(strtolower($regs[2]), static::$_irregular), 1);
<add>
<ide> return static::$_cache['singularize'][$word];
<ide> }
<ide>
<ide> public static function singularize($word)
<ide>
<ide> if (preg_match('/^(' . static::$_cache['uninflected'] . ')$/i', $word, $regs)) {
<ide> static::$_cache['pluralize'][$word] = $word;
<add>
<ide> return $word;
<ide> }
<ide>
<ide> foreach (static::$_singular as $rule => $replacement) {
<ide> if (preg_match($rule, $word)) {
<ide> static::$_cache['singularize'][$word] = preg_replace($rule, $replacement, $word);
<add>
<ide> return static::$_cache['singularize'][$word];
<ide> }
<ide> }
<ide> static::$_cache['singularize'][$word] = $word;
<add>
<ide> return $word;
<ide> }
<ide>
<ide> public static function slug($string, $replacement = '-')
<ide> array_values(static::$_transliteration),
<ide> $string
<ide> );
<add>
<ide> return preg_replace(array_keys($map), array_values($map), $string);
<ide> }
<ide> }
<ide><path>src/Utility/MergeVariablesTrait.php
<ide> protected function _mergePropertyData($current, $parent, $isAssoc)
<ide> $current[$key] = $value;
<ide> }
<ide> }
<add>
<ide> return $current;
<ide> }
<ide> }
<ide><path>src/Utility/Security.php
<ide> public static function randomBytes($length)
<ide> E_USER_WARNING
<ide> );
<ide> }
<add>
<ide> return $bytes;
<ide> }
<ide> trigger_error(
<ide> public static function randomBytes($length)
<ide> 'Falling back to an insecure random source.',
<ide> E_USER_WARNING
<ide> );
<add>
<ide> return static::insecureRandomBytes($length);
<ide> }
<ide>
<ide> public static function rijndael($text, $key, $operation)
<ide> throw new InvalidArgumentException('You must use a key larger than 32 bytes for Security::rijndael()');
<ide> }
<ide> $crypto = static::engine();
<add>
<ide> return $crypto->rijndael($text, $key, $operation);
<ide> }
<ide>
<ide> public static function encrypt($plain, $key, $hmacSalt = null)
<ide> $crypto = static::engine();
<ide> $ciphertext = $crypto->encrypt($plain, $key);
<ide> $hmac = hash_hmac('sha256', $ciphertext, $key);
<add>
<ide> return $hmac . $ciphertext;
<ide> }
<ide>
<ide> public static function decrypt($cipher, $key, $hmacSalt = null)
<ide> }
<ide>
<ide> $crypto = static::engine();
<add>
<ide> return $crypto->decrypt($cipher, $key);
<ide> }
<ide>
<ide> protected static function _constantEquals($hmac, $compare)
<ide> for ($i = 0; $i < $hashLength; $i++) {
<ide> $result |= (ord($hmac[$i]) ^ ord($compare[$i]));
<ide> }
<add>
<ide> return $result === 0;
<ide> }
<ide>
<ide> public static function salt($salt = null)
<ide> if ($salt === null) {
<ide> return static::$_salt;
<ide> }
<add>
<ide> return static::$_salt = (string)$salt;
<ide> }
<ide> }
<ide><path>src/Utility/Text.php
<ide> public static function insert($str, $data, array $options = [])
<ide> $offset = $pos + strlen($val);
<ide> $str = substr_replace($str, $val, $pos, 1);
<ide> }
<add>
<ide> return ($options['clean']) ? static::cleanInsert($str, $options) : $str;
<ide> }
<ide>
<ide> public static function insert($str, $data, array $options = [])
<ide> if (!isset($options['format']) && isset($options['before'])) {
<ide> $str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
<ide> }
<add>
<ide> return ($options['clean']) ? static::cleanInsert($str, $options) : $str;
<ide> }
<ide>
<ide> public static function cleanInsert($str, array $options)
<ide> $str = preg_replace($kleenex, $clean['replacement'], $str);
<ide> break;
<ide> }
<add>
<ide> return $str;
<ide> }
<ide>
<ide> public static function wrap($text, $options = [])
<ide> }
<ide> $wrapped = implode("\n", $chunks);
<ide> }
<add>
<ide> return $wrapped;
<ide> }
<ide>
<ide> public static function wrapBlock($text, $options = [])
<ide> if (!empty($options['indentAt']) && $options['indentAt'] === 0) {
<ide> $indentLength = !empty($options['indent']) ? strlen($options['indent']) : 0;
<ide> $options['width'] = $options['width'] - $indentLength;
<add>
<ide> return self::wrap($text, $options);
<ide> }
<ide>
<ide> public static function wrapBlock($text, $options = [])
<ide> $chunks = array_merge($chunks, $newChunks);
<ide> $wrapped = implode("\n", $chunks);
<ide> }
<add>
<ide> return $wrapped;
<ide> }
<ide>
<ide> public static function wordWrap($text, $width = 72, $break = "\n", $cut = false)
<ide> foreach ($paragraphs as &$paragraph) {
<ide> $paragraph = static::_wordWrap($paragraph, $width, $break, $cut);
<ide> }
<add>
<ide> return implode($break, $paragraphs);
<ide> }
<ide>
<ide> protected static function _wordWrap($text, $width = 72, $break = "\n", $cut = fa
<ide> $parts[] = trim($part);
<ide> $text = trim(mb_substr($text, mb_strlen($part)));
<ide> }
<add>
<ide> return implode($break, $parts);
<ide> }
<ide>
<ide> protected static function _strlen($text, array $options)
<ide> $pattern,
<ide> function ($match) use ($strlen) {
<ide> $utf8 = html_entity_decode($match[0], ENT_HTML5 | ENT_QUOTES, 'UTF-8');
<add>
<ide> return str_repeat(' ', $strlen($utf8, 'UTF-8'));
<ide> },
<ide> $text
<ide> );
<add>
<ide> return $strlen($replace);
<ide> }
<ide>
<ide> protected static function _removeLastWord($text)
<ide> if (mb_strwidth($lastWord) === mb_strlen($lastWord)) {
<ide> $text = mb_substr($text, 0, $spacepos);
<ide> }
<add>
<ide> return $text;
<ide> }
<ide>
<ide> public static function isMultibyte($string)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function utf8($string)
<ide> }
<ide> }
<ide> }
<add>
<ide> return $map;
<ide> }
<ide>
<ide> public static function ascii(array $array)
<ide> $ascii .= chr(128 + ($utf8 % 64));
<ide> }
<ide> }
<add>
<ide> return $ascii;
<ide> }
<ide>
<ide> public static function parseFileSize($size, $default = false)
<ide> }
<ide> if ($i !== false) {
<ide> $size = substr($size, 0, $l);
<add>
<ide> return $size * pow(1024, $i + 1);
<ide> }
<ide>
<ide> if (substr($size, -1) === 'B' && ctype_digit(substr($size, 0, -1))) {
<ide> $size = substr($size, 0, -1);
<add>
<ide> return (int)$size;
<ide> }
<ide>
<ide> public static function setTransliteratorId($transliteratorId)
<ide> public static function transliterate($string, $transliteratorId = null)
<ide> {
<ide> $transliteratorId = $transliteratorId ?: static::$_defaultTransliteratorId;
<add>
<ide> return transliterator_transliterate($transliteratorId, $string);
<ide> }
<ide>
<ide><path>src/Utility/Xml.php
<ide> protected static function _loadXml($input, $options)
<ide> if ($xml === null) {
<ide> throw new XmlException('Xml cannot be read.');
<ide> }
<add>
<ide> return $xml;
<ide> }
<ide>
<ide> public static function fromArray($input, $options = [])
<ide> if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
<ide> return new SimpleXMLElement($dom->saveXML());
<ide> }
<add>
<ide> return $dom;
<ide> }
<ide>
<ide> public static function toArray($obj)
<ide> $result = [];
<ide> $namespaces = array_merge(['' => ''], $obj->getNamespaces(true));
<ide> static::_toArray($obj, $result, '', array_keys($namespaces));
<add>
<ide> return $result;
<ide> }
<ide>
<ide><path>src/Validation/RulesProvider.php
<ide> public function __call($method, $arguments)
<ide> $arguments = array_slice($arguments, 0, -1);
<ide> }
<ide> $object = is_string($this->_class) ? null : $this->_class;
<add>
<ide> return $method->invokeArgs($object, $arguments);
<ide> }
<ide> }
<ide><path>src/Validation/Validation.php
<ide> class Validation
<ide> public static function notEmpty($check)
<ide> {
<ide> trigger_error('Validation::notEmpty() is deprecated. Use Validation::notBlank() instead.', E_USER_DEPRECATED);
<add>
<ide> return static::notBlank($check);
<ide> }
<ide>
<ide> public static function notBlank($check)
<ide> if (empty($check) && $check !== '0' && $check !== 0) {
<ide> return false;
<ide> }
<add>
<ide> return static::_check($check, '/[^\s]+/m');
<ide> }
<ide>
<ide> public static function alphaNumeric($check)
<ide> if (empty($check) && $check !== '0') {
<ide> return false;
<ide> }
<add>
<ide> return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
<ide> }
<ide>
<ide> public static function lengthBetween($check, $min, $max)
<ide> return false;
<ide> }
<ide> $length = mb_strlen($check);
<add>
<ide> return ($length >= $min && $length <= $max);
<ide> }
<ide>
<ide> public static function lengthBetween($check, $min, $max)
<ide> public static function blank($check)
<ide> {
<ide> trigger_error('Validation::blank() is deprecated.', E_USER_DEPRECATED);
<add>
<ide> return !static::_check($check, '/[^\\s]/');
<ide> }
<ide>
<ide> public static function cc($check, $type = 'fast', $deep = false, $regex = null)
<ide> return static::luhn($check);
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function numElements($check, $operator, $expectedCount)
<ide> if (!is_array($check) && !$check instanceof \Countable) {
<ide> return false;
<ide> }
<add>
<ide> return self::comparison(count($check), $operator, $expectedCount);
<ide> }
<ide>
<ide> public static function comparison($check1, $operator, $check2)
<ide> default:
<ide> static::$errors[] = 'You must define the $operator parameter for Validation::comparison()';
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function compareWith($check, $field, $context)
<ide> if (!isset($context['data'][$field])) {
<ide> return false;
<ide> }
<add>
<ide> return $context['data'][$field] === $check;
<ide> }
<ide>
<ide> public static function containsNonAlphaNumeric($check, $count = 1)
<ide> }
<ide>
<ide> $matches = preg_match_all('/[^a-zA-Z0-9]/', $check);
<add>
<ide> return $matches >= $count;
<ide> }
<ide>
<ide> public static function custom($check, $regex = null)
<ide> {
<ide> if ($regex === null) {
<ide> static::$errors[] = 'You must define a regular expression for Validation::custom()';
<add>
<ide> return false;
<ide> }
<add>
<ide> return static::_check($check, $regex);
<ide> }
<ide>
<ide> public static function date($check, $format = 'ymd', $regex = null)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function datetime($check, $dateFormat = 'ymd', $regex = null)
<ide> $time = implode(' ', $parts);
<ide> $valid = static::date($date, $dateFormat, $regex) && static::time($time);
<ide> }
<add>
<ide> return $valid;
<ide> }
<ide>
<ide> public static function time($check)
<ide> if (is_array($check)) {
<ide> $check = static::_getDateString($check);
<ide> }
<add>
<ide> return static::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
<ide> }
<ide>
<ide> public static function localizedTime($check, $type = 'datetime', $format = null)
<ide> throw new \InvalidArgumentException('Unsupported parser type given.');
<ide> }
<ide> $method = $methods[$type];
<add>
<ide> return (Time::$method($check, $format) !== null);
<ide> }
<ide>
<ide> public static function localizedTime($check, $type = 'datetime', $format = null)
<ide> public static function boolean($check)
<ide> {
<ide> $booleanList = [0, 1, '0', '1', true, false];
<add>
<ide> return in_array($check, $booleanList, true);
<ide> }
<ide>
<ide> public static function email($check, $deep = false, $regex = null)
<ide> if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
<ide> return true;
<ide> }
<add>
<ide> return is_array(gethostbynamel($regs[1]));
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'j
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public static function ip($check, $type = 'both')
<ide> if ($type === 'ipv6') {
<ide> $flags = FILTER_FLAG_IPV6;
<ide> }
<add>
<ide> return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
<ide> }
<ide>
<ide> public static function money($check, $symbolPosition = 'left')
<ide> } else {
<ide> $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
<ide> }
<add>
<ide> return static::_check($check, $regex);
<ide> }
<ide>
<ide> public static function multiple($check, array $options = [], $caseInsensitive =
<ide> }
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public static function numeric($check)
<ide> public static function naturalNumber($check, $allowZero = false)
<ide> {
<ide> $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
<add>
<ide> return static::_check($check, $regex);
<ide> }
<ide>
<ide> public static function range($check, $lower = null, $upper = null)
<ide> if (isset($lower, $upper)) {
<ide> return ($check >= $lower && $check <= $upper);
<ide> }
<add>
<ide> return is_finite($check);
<ide> }
<ide>
<ide> public static function url($check, $strict = false)
<ide> '(?:\/?|\/' . $validChars . '*)?' .
<ide> '(?:\?' . $validChars . '*)?' .
<ide> '(?:#' . $validChars . '*)?$/iu';
<add>
<ide> return static::_check($check, $regex);
<ide> }
<ide>
<ide> public static function inList($check, array $list, $caseInsensitive = false)
<ide> } else {
<ide> $list = array_map('strval', $list);
<ide> }
<add>
<ide> return in_array((string)$check, $list, true);
<ide> }
<ide>
<ide> public static function userDefined($check, $object, $method, $args = null)
<ide> 'Validation::userDefined() is deprecated. Just set a callable for `rule` key when adding validators instead.',
<ide> E_USER_DEPRECATED
<ide> );
<add>
<ide> return call_user_func_array([$object, $method], [$check, $args]);
<ide> }
<ide>
<ide> public static function userDefined($check, $object, $method, $args = null)
<ide> public static function uuid($check)
<ide> {
<ide> $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[0-5][a-fA-F0-9]{3}-[089aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/';
<add>
<ide> return self::_check($check, $regex);
<ide> }
<ide>
<ide> public static function mimeType($check, $mimeTypes = [])
<ide> foreach ($mimeTypes as $key => $val) {
<ide> $mimeTypes[$key] = strtolower($val);
<ide> }
<add>
<ide> return in_array($mime, $mimeTypes);
<ide> }
<ide>
<ide> public static function uploadError($check, $allowNoFile = false)
<ide> if ($allowNoFile) {
<ide> return in_array((int)$check, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
<ide> }
<add>
<ide> return (int)$check === UPLOAD_ERR_OK;
<ide> }
<ide>
<ide> public static function uploadedFile($file, array $options = [])
<ide> if (isset($options['types']) && !static::mimeType($file, $options['types'])) {
<ide> return false;
<ide> }
<add>
<ide> return is_uploaded_file($file['tmp_name']);
<ide> }
<ide>
<ide> public static function geoCoordinate($value, array $options = [])
<ide> if ($options['format'] === 'lat') {
<ide> $pattern = '/^' . self::$_pattern['latitude'] . '$/';
<ide> }
<add>
<ide> return (bool)preg_match($pattern, $value);
<ide> }
<ide>
<ide> public static function geoCoordinate($value, array $options = [])
<ide> public static function latitude($value, array $options = [])
<ide> {
<ide> $options['format'] = 'lat';
<add>
<ide> return self::geoCoordinate($value, $options);
<ide> }
<ide>
<ide> public static function latitude($value, array $options = [])
<ide> public static function longitude($value, array $options = [])
<ide> {
<ide> $options['format'] = 'long';
<add>
<ide> return self::geoCoordinate($value, $options);
<ide> }
<ide>
<ide> public static function ascii($value)
<ide> if (!is_string($value)) {
<ide> return false;
<ide> }
<add>
<ide> return strlen($value) <= mb_strlen($value, 'utf-8');
<ide> }
<ide>
<ide> public static function utf8($value, array $options = [])
<ide> if ($options['extended']) {
<ide> return true;
<ide> }
<add>
<ide> return preg_match('/[\x{10000}-\x{10FFFF}]/u', $value) === 0;
<ide> }
<ide>
<ide> public static function isInteger($value)
<ide> if (is_int($value)) {
<ide> return true;
<ide> }
<add>
<ide> return (bool)preg_match('/^-?[0-9]+$/', $value);
<ide> }
<ide>
<ide><path>src/Validation/ValidationRule.php
<ide> public function process($value, array $providers, array $context = [])
<ide> if ($result === false) {
<ide> return $this->_message ?: false;
<ide> }
<add>
<ide> return $result;
<ide> }
<ide>
<ide> protected function _skip($context)
<ide> {
<ide> if (!is_string($this->_on) && is_callable($this->_on)) {
<ide> $function = $this->_on;
<add>
<ide> return !$function($context);
<ide> }
<ide>
<ide> protected function _skip($context)
<ide> return true;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>src/Validation/ValidationSet.php
<ide> public function isPresenceRequired($validatePresent = null)
<ide> if ($validatePresent === null) {
<ide> return $this->_validatePresent;
<ide> }
<add>
<ide> return $this->_validatePresent = $validatePresent;
<ide> }
<ide>
<ide> public function isEmptyAllowed($allowEmpty = null)
<ide> if ($allowEmpty === null) {
<ide> return $this->_allowEmpty;
<ide> }
<add>
<ide> return $this->_allowEmpty = $allowEmpty;
<ide> }
<ide>
<ide> public function add($name, $rule)
<ide> $rule = new ValidationRule($rule);
<ide> }
<ide> $this->_rules[$name] = $rule;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function add($name, $rule)
<ide> public function remove($name)
<ide> {
<ide> unset($this->_rules[$name]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/Validation/Validator.php
<ide> public function field($name, ValidationSet $set = null)
<ide> $set = $set ?: new ValidationSet;
<ide> $this->_fields[$name] = $set;
<ide> }
<add>
<ide> return $this->_fields[$name];
<ide> }
<ide>
<ide> public function provider($name, $object = null)
<ide> if ($name === 'default') {
<ide> return $this->_providers[$name] = new RulesProvider;
<ide> }
<add>
<ide> return null;
<ide> }
<ide> $this->_providers[$name] = $object;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addNested($field, Validator $validator)
<ide> $validator->provider($provider, $this->provider($provider));
<ide> }
<ide> $errors = $validator->errors($value, $context['newRecord']);
<add>
<ide> return empty($errors) ? true : $errors;
<ide> }]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function addNestedMany($field, Validator $validator)
<ide> $errors[$i] = $check;
<ide> }
<ide> }
<add>
<ide> return empty($errors) ? true : $errors;
<ide> }]);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function remove($field, $rule = null)
<ide> } else {
<ide> $this->field($field)->remove($rule);
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function requirePresence($field, $mode = true, $message = null)
<ide> if ($message) {
<ide> $this->_presenceMessages[$field] = $message;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function allowEmpty($field, $when = true, $message = null)
<ide> if ($message) {
<ide> $this->_allowEmptyMessages[$field] = $message;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function notEmpty($field, $message = null, $when = false)
<ide> if ($message) {
<ide> $this->_allowEmptyMessages[$field] = $message;
<ide> }
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function notEmpty($field, $message = null, $when = false)
<ide> public function notBlank($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'notBlank', $extra + [
<ide> 'rule' => 'notBlank',
<ide> ]);
<ide> public function notBlank($field, $message = null, $when = null)
<ide> public function alphaNumeric($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'alphaNumeric', $extra + [
<ide> 'rule' => 'alphaNumeric',
<ide> ]);
<ide> public function lengthBetween($field, array $range, $message = null, $when = nul
<ide> throw new InvalidArgumentException('The $range argument requires 2 numbers');
<ide> }
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'lengthBetween', $extra + [
<ide> 'rule' => ['lengthBetween', array_shift($range), array_shift($range)],
<ide> ]);
<ide> public function lengthBetween($field, array $range, $message = null, $when = nul
<ide> public function creditCard($field, $type = 'all', $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'creditCard', $extra + [
<ide> 'rule' => ['cc', $type, true],
<ide> ]);
<ide> public function creditCard($field, $type = 'all', $message = null, $when = null)
<ide> public function greaterThan($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'greaterThan', $extra + [
<ide> 'rule' => ['comparison', '>', $value]
<ide> ]);
<ide> public function greaterThan($field, $value, $message = null, $when = null)
<ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'greaterThanOrEqual', $extra + [
<ide> 'rule' => ['comparison', '>=', $value]
<ide> ]);
<ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null
<ide> public function lessThan($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'lessThan', $extra + [
<ide> 'rule' => ['comparison', '<', $value]
<ide> ]);
<ide> public function lessThan($field, $value, $message = null, $when = null)
<ide> public function lessThanOrEqual($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'lessThanOrEqual', $extra + [
<ide> 'rule' => ['comparison', '<=', $value]
<ide> ]);
<ide> public function lessThanOrEqual($field, $value, $message = null, $when = null)
<ide> public function equals($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'equals', $extra + [
<ide> 'rule' => ['comparison', '=', $value]
<ide> ]);
<ide> public function equals($field, $value, $message = null, $when = null)
<ide> public function notEquals($field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'notEquals', $extra + [
<ide> 'rule' => ['comparison', '!=', $value]
<ide> ]);
<ide> public function notEquals($field, $value, $message = null, $when = null)
<ide> public function sameAs($field, $secondField, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'sameAs', $extra + [
<ide> 'rule' => ['compareWith', $secondField]
<ide> ]);
<ide> public function sameAs($field, $secondField, $message = null, $when = null)
<ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'containsNonAlphaNumeric', $extra + [
<ide> 'rule' => ['containsNonAlphaNumeric', $limit]
<ide> ]);
<ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $wh
<ide> public function date($field, $formats = ['ymd'], $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'date', $extra + [
<ide> 'rule' => ['date', $formats]
<ide> ]);
<ide> public function date($field, $formats = ['ymd'], $message = null, $when = null)
<ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'dateTime', $extra + [
<ide> 'rule' => ['datetime', $formats]
<ide> ]);
<ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = nu
<ide> public function time($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'time', $extra + [
<ide> 'rule' => 'time'
<ide> ]);
<ide> public function time($field, $message = null, $when = null)
<ide> public function localizedTime($field, $type = 'datetime', $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'localizedTime', $extra + [
<ide> 'rule' => ['localizedTime', $type]
<ide> ]);
<ide> public function localizedTime($field, $type = 'datetime', $message = null, $when
<ide> public function boolean($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'boolean', $extra + [
<ide> 'rule' => 'boolean'
<ide> ]);
<ide> public function boolean($field, $message = null, $when = null)
<ide> public function decimal($field, $places = null, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'decimal', $extra + [
<ide> 'rule' => ['decimal', $places]
<ide> ]);
<ide> public function decimal($field, $places = null, $message = null, $when = null)
<ide> public function email($field, $checkMX = false, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'email', $extra + [
<ide> 'rule' => ['email', $checkMX]
<ide> ]);
<ide> public function email($field, $checkMX = false, $message = null, $when = null)
<ide> public function ip($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'ip', $extra + [
<ide> 'rule' => 'ip'
<ide> ]);
<ide> public function ip($field, $message = null, $when = null)
<ide> public function ipv4($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'ipv4', $extra + [
<ide> 'rule' => ['ip', 'ipv4']
<ide> ]);
<ide> public function ipv4($field, $message = null, $when = null)
<ide> public function ipv6($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'ipv6', $extra + [
<ide> 'rule' => ['ip', 'ipv6']
<ide> ]);
<ide> public function ipv6($field, $message = null, $when = null)
<ide> public function minLength($field, $min, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'minLength', $extra + [
<ide> 'rule' => ['minLength', $min]
<ide> ]);
<ide> public function minLength($field, $min, $message = null, $when = null)
<ide> public function maxLength($field, $max, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'maxLength', $extra + [
<ide> 'rule' => ['maxLength', $max]
<ide> ]);
<ide> public function maxLength($field, $max, $message = null, $when = null)
<ide> public function numeric($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'numeric', $extra + [
<ide> 'rule' => 'numeric'
<ide> ]);
<ide> public function numeric($field, $message = null, $when = null)
<ide> public function naturalNumber($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'naturalNumber', $extra + [
<ide> 'rule' => ['naturalNumber', false]
<ide> ]);
<ide> public function naturalNumber($field, $message = null, $when = null)
<ide> public function nonNegativeInteger($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'nonNegativeInteger', $extra + [
<ide> 'rule' => ['naturalNumber', true]
<ide> ]);
<ide> public function range($field, array $range, $message = null, $when = null)
<ide> throw new InvalidArgumentException('The $range argument requires 2 numbers');
<ide> }
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'range', $extra + [
<ide> 'rule' => ['range', array_shift($range), array_shift($range)]
<ide> ]);
<ide> public function range($field, array $range, $message = null, $when = null)
<ide> public function url($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'url', $extra + [
<ide> 'rule' => ['url', false]
<ide> ]);
<ide> public function url($field, $message = null, $when = null)
<ide> public function urlWithProtocol($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'urlWithProtocol', $extra + [
<ide> 'rule' => ['url', true]
<ide> ]);
<ide> public function urlWithProtocol($field, $message = null, $when = null)
<ide> public function inList($field, array $list, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'inList', $extra + [
<ide> 'rule' => ['inList', $list]
<ide> ]);
<ide> public function inList($field, array $list, $message = null, $when = null)
<ide> public function uuid($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'uuid', $extra + [
<ide> 'rule' => 'uuid'
<ide> ]);
<ide> public function uuid($field, $message = null, $when = null)
<ide> public function uploadedFile($field, array $options, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'uploadedFile', $extra + [
<ide> 'rule' => ['uploadedFile', $options]
<ide> ]);
<ide> public function uploadedFile($field, array $options, $message = null, $when = nu
<ide> public function latLong($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'latLong', $extra + [
<ide> 'rule' => 'geoCoordinate'
<ide> ]);
<ide> public function latLong($field, $message = null, $when = null)
<ide> public function latitude($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'latitude', $extra + [
<ide> 'rule' => 'latitude'
<ide> ]);
<ide> public function latitude($field, $message = null, $when = null)
<ide> public function longitude($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'longitude', $extra + [
<ide> 'rule' => 'longitude'
<ide> ]);
<ide> public function longitude($field, $message = null, $when = null)
<ide> public function ascii($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'ascii', $extra + [
<ide> 'rule' => 'ascii'
<ide> ]);
<ide> public function ascii($field, $message = null, $when = null)
<ide> public function utf8($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'utf8', $extra + [
<ide> 'rule' => ['utf8', ['extended' => false]]
<ide> ]);
<ide> public function utf8($field, $message = null, $when = null)
<ide> public function utf8Extended($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'utf8Extended', $extra + [
<ide> 'rule' => ['utf8', ['extended' => true]]
<ide> ]);
<ide> public function utf8Extended($field, $message = null, $when = null)
<ide> public function integer($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'integer', $extra + [
<ide> 'rule' => 'isInteger'
<ide> ]);
<ide> public function integer($field, $message = null, $when = null)
<ide> public function isArray($field, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'isArray', $extra + [
<ide> 'rule' => 'isArray'
<ide> ]);
<ide> public function multipleOptions($field, array $options = [], $message = null, $w
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide> $caseInsensitive = isset($options['caseInsenstive']) ? $options['caseInsensitive'] : false;
<ide> unset($options['caseInsensitive']);
<add>
<ide> return $this->add($field, 'multipleOptions', $extra + [
<ide> 'rule' => ['multiple', $options, $caseInsensitive]
<ide> ]);
<ide> public function multipleOptions($field, array $options = [], $message = null, $w
<ide> public function hasAtLeast($field, $count, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'hasAtLeast', $extra + [
<ide> 'rule' => function ($value) use ($count) {
<ide> if (is_array($value) && isset($value['_ids'])) {
<ide> $value = $value['_ids'];
<ide> }
<add>
<ide> return Validation::numElements($value, '>=', $count);
<ide> }
<ide> ]);
<ide> public function hasAtLeast($field, $count, $message = null, $when = null)
<ide> public function hasAtMost($field, $count, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<add>
<ide> return $this->add($field, 'hasAtMost', $extra + [
<ide> 'rule' => function ($value) use ($count) {
<ide> if (is_array($value) && isset($value['_ids'])) {
<ide> $value = $value['_ids'];
<ide> }
<add>
<ide> return Validation::numElements($value, '<=', $count);
<ide> }
<ide> ]);
<ide> public function isEmptyAllowed($field, $newRecord)
<ide> $providers = $this->_providers;
<ide> $data = [];
<ide> $context = compact('data', 'newRecord', 'field', 'providers');
<add>
<ide> return $this->_canBeEmpty($this->field($field), $context);
<ide> }
<ide>
<ide> public function isPresenceRequired($field, $newRecord)
<ide> $providers = $this->_providers;
<ide> $data = [];
<ide> $context = compact('data', 'newRecord', 'field', 'providers');
<add>
<ide> return !$this->_checkPresence($this->field($field), $context);
<ide> }
<ide>
<ide> protected function _fieldIsEmpty($data)
<ide> $isArray = is_array($data);
<ide> if ($isArray && (isset($data['year']) || isset($data['hour']))) {
<ide> $value = implode('', $data);
<add>
<ide> return strlen($value) === 0;
<ide> }
<ide> if ($isArray && isset($data['name'], $data['type'], $data['tmp_name'], $data['error'])) {
<ide> return (int)$data['error'] === UPLOAD_ERR_NO_FILE;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _processRules($field, ValidationSet $rules, $data, $newRecord
<ide> break;
<ide> }
<ide> }
<add>
<ide> return $errors;
<ide> }
<ide>
<ide> public function __debugInfo()
<ide> 'rules' => array_keys($fieldSet->rules()),
<ide> ];
<ide> }
<add>
<ide> return [
<ide> '_presenceMessages' => $this->_presenceMessages,
<ide> '_allowEmptyMessages' => $this->_allowEmptyMessages,
<ide><path>src/Validation/ValidatorAwareTrait.php
<ide> public function validator($name = null, Validator $validator = null)
<ide> }
<ide>
<ide> $validator->provider(self::VALIDATOR_PROVIDER_NAME, $this);
<add>
<ide> return $this->_validators[$name] = $validator;
<ide> }
<ide>
<ide><path>src/View/Cell.php
<ide> public function render($template = null)
<ide> if ($cache) {
<ide> return Cache::remember($cache['key'], $render, $cache['config']);
<ide> }
<add>
<ide> return $render();
<ide> }
<ide>
<ide> protected function _cacheConfig($action)
<ide> if ($this->_cache === true) {
<ide> return $default;
<ide> }
<add>
<ide> return $this->_cache + $default;
<ide> }
<ide>
<ide> public function __toString()
<ide> return $this->render();
<ide> } catch (Exception $e) {
<ide> trigger_error(sprintf('Could not render cell - %s [%s, line %d]', $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_WARNING);
<add>
<ide> return '';
<ide> }
<ide> }
<ide><path>src/View/CellTrait.php
<ide> protected function _createCell($className, $action, $plugin, $options)
<ide> $class = get_class($this);
<ide> $builder->className($class);
<ide> $instance->viewClass = $class;
<add>
<ide> return $instance;
<ide> }
<ide>
<ide> protected function _createCell($className, $action, $plugin, $options)
<ide> $builder->className($this->viewClass);
<ide> $instance->viewClass = $this->viewClass;
<ide> }
<add>
<ide> return $instance;
<ide> }
<ide> }
<ide><path>src/View/Form/ArrayContext.php
<ide> public function primaryKey()
<ide> return isset($data['columns']) ? (array)$data['columns'] : [];
<ide> }
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> public function primaryKey()
<ide> public function isPrimaryKey($field)
<ide> {
<ide> $primaryKey = $this->primaryKey();
<add>
<ide> return in_array($field, $primaryKey);
<ide> }
<ide>
<ide> public function isCreate()
<ide> return false;
<ide> }
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function val($field)
<ide> if (empty($this->_context['defaults']) || !is_array($this->_context['defaults'])) {
<ide> return null;
<ide> }
<add>
<ide> return Hash::get($this->_context['defaults'], $field);
<ide> }
<ide>
<ide> public function isRequired($field)
<ide> return false;
<ide> }
<ide> $required = Hash::get($this->_context['required'], $field);
<add>
<ide> return (bool)$required;
<ide> }
<ide>
<ide> public function fieldNames()
<ide> {
<ide> $schema = $this->_context['schema'];
<ide> unset($schema['_constraints'], $schema['_indexes']);
<add>
<ide> return array_keys($schema);
<ide> }
<ide>
<ide> public function type($field)
<ide> return null;
<ide> }
<ide> $schema = Hash::get($this->_context['schema'], $field);
<add>
<ide> return isset($schema['type']) ? $schema['type'] : null;
<ide> }
<ide>
<ide> public function attributes($field)
<ide> }
<ide> $schema = (array)Hash::get($this->_context['schema'], $field);
<ide> $whitelist = ['length' => null, 'precision' => null];
<add>
<ide> return array_intersect_key($schema, $whitelist);
<ide> }
<ide>
<ide> public function hasError($field)
<ide> if (empty($this->_context['errors'])) {
<ide> return false;
<ide> }
<add>
<ide> return (bool)Hash::check($this->_context['errors'], $field);
<ide> }
<ide>
<ide> public function error($field)
<ide> if (empty($this->_context['errors'])) {
<ide> return [];
<ide> }
<add>
<ide> return Hash::get($this->_context['errors'], $field);
<ide> }
<ide> }
<ide><path>src/View/Form/EntityContext.php
<ide> public function isPrimaryKey($field)
<ide> $parts = explode('.', $field);
<ide> $table = $this->_getTable($parts);
<ide> $primaryKey = (array)$table->primaryKey();
<add>
<ide> return in_array(array_pop($parts), $primaryKey);
<ide> }
<ide>
<ide> public function isCreate()
<ide> if ($entity instanceof EntityInterface) {
<ide> return $entity->isNew() !== false;
<ide> }
<add>
<ide> return true;
<ide> }
<ide>
<ide> public function val($field)
<ide> }
<ide> if (is_array($entity)) {
<ide> $key = array_pop($parts);
<add>
<ide> return isset($entity[$key]) ? $entity[$key] : null;
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> protected function _extractMultiple($values, $path)
<ide> }
<ide> $table = $this->_getTable($path, false);
<ide> $primary = $table ? (array)$table->primaryKey() : ['id'];
<add>
<ide> return (new Collection($values))->extract($primary[0])->toArray();
<ide> }
<ide>
<ide> public function entity($path = null)
<ide>
<ide> if (!$isLast && $next === null && $prop !== '_ids') {
<ide> $table = $this->_getTable($path);
<add>
<ide> return $table->newEntity();
<ide> }
<ide>
<ide> protected function _getProp($target, $field)
<ide> return $val;
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide> }
<ide> public function isRequired($field)
<ide> if ($this->type($field) !== 'boolean') {
<ide> return $validator->isEmptyAllowed($fieldName, $isNew) === false;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function isRequired($field)
<ide> public function fieldNames()
<ide> {
<ide> $table = $this->_getTable('0');
<add>
<ide> return $table->schema()->columns();
<ide> }
<ide>
<ide> protected function _getValidator($parts)
<ide>
<ide> if (isset($this->_validator[$key])) {
<ide> $this->_validator[$key]->provider('entity', $entity);
<add>
<ide> return $this->_validator[$key];
<ide> }
<ide>
<ide> protected function _getValidator($parts)
<ide>
<ide> $validator = $table->validator($method);
<ide> $validator->provider('entity', $entity);
<add>
<ide> return $this->_validator[$key] = $validator;
<ide> }
<ide>
<ide> public function type($field)
<ide> {
<ide> $parts = explode('.', $field);
<ide> $table = $this->_getTable($parts);
<add>
<ide> return $table->schema()->baseColumnType(array_pop($parts));
<ide> }
<ide>
<ide> public function attributes($field)
<ide> $table = $this->_getTable($parts);
<ide> $column = (array)$table->schema()->column(array_pop($parts));
<ide> $whitelist = ['length' => null, 'precision' => null];
<add>
<ide> return array_intersect_key($column, $whitelist);
<ide> }
<ide>
<ide> public function error($field)
<ide> if ($entity instanceof EntityInterface) {
<ide> return $entity->errors(array_pop($parts));
<ide> }
<add>
<ide> return [];
<ide> }
<ide> }
<ide><path>src/View/Form/FormContext.php
<ide> public function isRequired($field)
<ide> if ($this->type($field) !== 'boolean') {
<ide> return $validator->isEmptyAllowed($field, $this->isCreate()) === false;
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function attributes($field)
<ide> {
<ide> $column = (array)$this->_form->schema()->field($field);
<ide> $whitelist = ['length' => null, 'precision' => null];
<add>
<ide> return array_intersect_key($column, $whitelist);
<ide> }
<ide>
<ide> public function attributes($field)
<ide> public function hasError($field)
<ide> {
<ide> $errors = $this->error($field);
<add>
<ide> return count($errors) > 0;
<ide> }
<ide>
<ide><path>src/View/Helper.php
<ide> public function __get($name)
<ide> if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
<ide> $config = ['enabled' => false] + (array)$this->_helperMap[$name]['config'];
<ide> $this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $config);
<add>
<ide> return $this->{$name};
<ide> }
<ide> }
<ide> protected function _confirm($message, $okCode, $cancelCode = '', $options = [])
<ide> if ($escape) {
<ide> $confirm = h($confirm);
<ide> }
<add>
<ide> return $confirm;
<ide> }
<ide>
<ide> public function addClass(array $options = [], $class = null, $key = 'class')
<ide> } else {
<ide> $options[$key] = $class;
<ide> }
<add>
<ide> return $options;
<ide> }
<ide>
<ide> public function implementedEvents()
<ide> $events[$event] = $method;
<ide> }
<ide> }
<add>
<ide> return $events;
<ide> }
<ide>
<ide><path>src/View/Helper/FormHelper.php
<ide> public function widgetRegistry(WidgetRegistry $instance = null, $widgets = [])
<ide> if ($this->_registry === null) {
<ide> $this->_registry = new WidgetRegistry($this->templater(), $this->_View, $widgets);
<ide> }
<add>
<ide> return $this->_registry;
<ide> }
<ide> $this->_registry = $instance;
<add>
<ide> return $this->_registry;
<ide> }
<ide>
<ide> protected function _isRequiredField($validationRules)
<ide> if ($rule->skip()) {
<ide> continue;
<ide> }
<add>
<ide> return !$validationRules->isEmptyAllowed();
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> public function create($model = null, array $options = [])
<ide> }
<ide>
<ide> $actionAttr = $templater->formatAttributes(['action' => $action, 'escape' => false]);
<add>
<ide> return $this->formatTemplate('formStart', [
<ide> 'attrs' => $templater->formatAttributes($htmlAttributes) . $actionAttr
<ide> ]) . $append;
<ide> protected function _formUrl($context, $options)
<ide> if (empty($action[0]) && isset($id)) {
<ide> $action[0] = $id;
<ide> }
<add>
<ide> return $action;
<ide> }
<ide>
<ide> protected function _csrfField()
<ide> if (empty($this->request->params['_csrfToken'])) {
<ide> return '';
<ide> }
<add>
<ide> return $this->hidden('_csrfToken', [
<ide> 'value' => $this->request->params['_csrfToken'],
<ide> 'secure' => static::SECURE_SKIP
<ide> public function end(array $secureAttributes = [])
<ide> $this->requestType = null;
<ide> $this->_context = null;
<ide> $this->_idPrefix = $this->config('idPrefix');
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function secure(array $fields = [], array $secureAttributes = [])
<ide> ]);
<ide> $out .= $this->hidden('_Token.debug', $tokenDebug);
<ide> }
<add>
<ide> return $this->formatTemplate('hiddenBlock', ['content' => $out]);
<ide> }
<ide>
<ide> public function error($field, $text = null, array $options = [])
<ide> $error = array_pop($error);
<ide> }
<ide> }
<add>
<ide> return $this->formatTemplate('error', ['content' => $error]);
<ide> }
<ide>
<ide> public function label($fieldName, $text = null, array $options = [])
<ide> if (is_array($options['input'])) {
<ide> $attrs = $options['input'] + $attrs;
<ide> }
<add>
<ide> return $this->widget('nestingLabel', $attrs);
<ide> }
<add>
<ide> return $this->widget('label', $attrs);
<ide> }
<ide>
<ide> public function fieldset($fields = '', array $options = [])
<ide> }
<ide> $out = $this->formatTemplate('fieldset', $fieldsetParams);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function input($fieldName, array $options = [])
<ide> if ($newTemplates) {
<ide> $templater->pop();
<ide> }
<add>
<ide> return $input;
<ide> }
<ide>
<ide> protected function _groupTemplate($options)
<ide> if (!$this->templater()->get($groupTemplate)) {
<ide> $groupTemplate = 'formGroup';
<ide> }
<add>
<ide> return $this->formatTemplate($groupTemplate, [
<ide> 'input' => $options['input'],
<ide> 'label' => $options['label'],
<ide> protected function _getInput($fieldName, $options)
<ide> case 'select':
<ide> $opts = $options['options'];
<ide> unset($options['options']);
<add>
<ide> return $this->select($fieldName, $opts, $options);
<ide> case 'radio':
<ide> $opts = $options['options'];
<ide> unset($options['options']);
<add>
<ide> return $this->radio($fieldName, $opts, $options);
<ide> case 'multicheckbox':
<ide> $opts = $options['options'];
<ide> unset($options['options']);
<add>
<ide> return $this->multiCheckbox($fieldName, $opts, $options);
<ide> default:
<ide> return $this->{$options['type']}($fieldName, $options);
<ide> protected function _parseOptions($fieldName, $options)
<ide> }
<ide>
<ide> $options = $this->_magicOptions($fieldName, $options, $needsMagicType);
<add>
<ide> return $options;
<ide> }
<ide>
<ide> protected function _optionsOptions($fieldName, $options)
<ide> $options['type'] = 'select';
<ide> }
<ide> $options['options'] = $varOptions;
<add>
<ide> return $options;
<ide> }
<ide>
<ide> protected function _getLabel($fieldName, $options)
<ide> if ($label === false) {
<ide> return false;
<ide> }
<add>
<ide> return $this->_inputLabel($fieldName, $label, $options);
<ide> }
<ide>
<ide> protected function _extractOption($name, $options, $default = null)
<ide> if (array_key_exists($name, $options)) {
<ide> return $options[$name];
<ide> }
<add>
<ide> return $default;
<ide> }
<ide>
<ide> protected function _inputLabel($fieldName, $label, $options)
<ide> if ($options['nestedInput']) {
<ide> $labelAttributes['input'] = $options['input'];
<ide> }
<add>
<ide> return $this->label($fieldName, $labelText, $labelAttributes);
<ide> }
<ide>
<ide> public function checkbox($fieldName, array $options = [])
<ide>
<ide> if ($options['hiddenField'] === '_split') {
<ide> unset($options['hiddenField'], $options['type']);
<add>
<ide> return ['hidden' => $output, 'input' => $this->widget('checkbox', $options)];
<ide> }
<ide> unset($options['hiddenField'], $options['type']);
<add>
<ide> return $output . $this->widget('checkbox', $options);
<ide> }
<ide>
<ide> public function __call($method, $params)
<ide> $options['type'] = $method;
<ide> }
<ide> $options = $this->_initInputField($params[0], $options);
<add>
<ide> return $this->widget($options['type'], $options);
<ide> }
<ide>
<ide> public function textarea($fieldName, array $options = [])
<ide> {
<ide> $options = $this->_initInputField($fieldName, $options);
<ide> unset($options['type']);
<add>
<ide> return $this->widget('textarea', $options);
<ide> }
<ide>
<ide> public function hidden($fieldName, array $options = [])
<ide> }
<ide>
<ide> $options['type'] = 'hidden';
<add>
<ide> return $this->widget('hidden', $options);
<ide> }
<ide>
<ide> public function file($fieldName, array $options = [])
<ide> $options = $this->_initInputField($fieldName, $options);
<ide>
<ide> unset($options['type']);
<add>
<ide> return $this->widget('file', $options);
<ide> }
<ide>
<ide> public function button($title, array $options = [])
<ide> {
<ide> $options += ['type' => 'submit', 'escape' => false, 'secure' => false];
<ide> $options['text'] = $title;
<add>
<ide> return $this->widget('button', $options);
<ide> }
<ide>
<ide> public function postButton($title, $url, array $options = [])
<ide> }
<ide> $out .= $this->button($title, $options);
<ide> $out .= $this->end();
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function postLink($title, $url = null, array $options = [])
<ide> $options['onclick'] .= 'event.returnValue = false; return false;';
<ide>
<ide> $out .= $this->Html->link($title, $url, $options);
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function select($fieldName, $options = [], array $attributes = [])
<ide>
<ide> if ($attributes['multiple'] === 'checkbox') {
<ide> unset($attributes['multiple'], $attributes['empty']);
<add>
<ide> return $this->multiCheckbox($fieldName, $options, $attributes);
<ide> }
<ide>
<ide> public function select($fieldName, $options = [], array $attributes = [])
<ide> $hidden = $this->hidden($fieldName, $hiddenAttributes);
<ide> }
<ide> unset($attributes['hiddenField'], $attributes['type']);
<add>
<ide> return $hidden . $this->widget('select', $attributes);
<ide> }
<ide>
<ide> public function multiCheckbox($fieldName, $options, array $attributes = [])
<ide> ];
<ide> $hidden = $this->hidden($fieldName, $hiddenAttributes);
<ide> }
<add>
<ide> return $hidden . $this->widget('multicheckbox', $attributes);
<ide> }
<ide>
<ide> protected function _singleDatetime($options, $keep)
<ide> if (isset($options['value'])) {
<ide> $options['val'] = $options['value'];
<ide> }
<add>
<ide> return $options;
<ide> }
<ide>
<ide> public function day($fieldName = null, array $options = [])
<ide> 'day' => (int)$options['val']
<ide> ];
<ide> }
<add>
<ide> return $this->dateTime($fieldName, $options);
<ide> }
<ide>
<ide> public function month($fieldName, array $options = [])
<ide> 'day' => date('d')
<ide> ];
<ide> }
<add>
<ide> return $this->dateTime($fieldName, $options);
<ide> }
<ide>
<ide> public function hour($fieldName, array $options = [])
<ide> 'minute' => date('i'),
<ide> ];
<ide> }
<add>
<ide> return $this->dateTime($fieldName, $options);
<ide> }
<ide>
<ide> public function minute($fieldName, array $options = [])
<ide> 'minute' => (int)$options['val'],
<ide> ];
<ide> }
<add>
<ide> return $this->dateTime($fieldName, $options);
<ide> }
<ide>
<ide> public function meridian($fieldName, array $options = [])
<ide> 'meridian' => $hour > 11 ? 'pm' : 'am',
<ide> ];
<ide> }
<add>
<ide> return $this->dateTime($fieldName, $options);
<ide> }
<ide>
<ide> public function dateTime($fieldName, array $options = [])
<ide> ];
<ide> $options = $this->_initInputField($fieldName, $options);
<ide> $options = $this->_datetimeOptions($options);
<add>
<ide> return $this->widget('datetime', $options);
<ide> }
<ide>
<ide> public function date($fieldName, array $options = [])
<ide>
<ide> $options = $this->_initInputField($fieldName, $options);
<ide> $options = $this->_datetimeOptions($options);
<add>
<ide> return $this->widget('datetime', $options);
<ide> }
<ide>
<ide> protected function _initInputField($field, $options = [])
<ide> if (!isset($options['required']) && empty($options['disabled']) && $context->isRequired($field)) {
<ide> $options['required'] = true;
<ide> }
<add>
<ide> return $options;
<ide> }
<ide>
<ide> protected function _secureFieldName($name)
<ide> $parts = array_map(function ($el) {
<ide> return trim($el, ']');
<ide> }, $parts);
<add>
<ide> return array_filter($parts, 'strlen');
<ide> }
<ide>
<ide> public function context($context = null)
<ide> if ($context instanceof ContextInterface) {
<ide> $this->_context = $context;
<ide> }
<add>
<ide> return $this->_getContext();
<ide> }
<ide>
<ide> protected function _getContext($data = [])
<ide> 'Context objects must implement Cake\View\Form\ContextInterface'
<ide> );
<ide> }
<add>
<ide> return $this->_context = $context;
<ide> }
<ide>
<ide> public function widget($name, array $data = [])
<ide> $this->_secure($secure, $this->_secureFieldName($field));
<ide> }
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide><path>src/View/Helper/HtmlHelper.php
<ide> public function __construct(View $View, array $config = [])
<ide> public function addCrumb($name, $link = null, array $options = [])
<ide> {
<ide> $this->_crumbs[] = [$name, $link, $options];
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function docType($type = 'html5')
<ide> if (isset($this->_docTypes[$type])) {
<ide> return $this->_docTypes[$type];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function charset($charset = null)
<ide> if (empty($charset)) {
<ide> $charset = strtolower(Configure::read('App.encoding'));
<ide> }
<add>
<ide> return $this->formatTemplate('charset', [
<ide> 'charset' => (!empty($charset) ? $charset : 'utf-8')
<ide> ]);
<ide> public function link($title, $url = null, array $options = [])
<ide> }
<ide>
<ide> $templater = $this->templater();
<add>
<ide> return $templater->format('link', [
<ide> 'url' => $url,
<ide> 'attrs' => $templater->formatAttributes($options),
<ide> public function css($path, array $options = [])
<ide> if (empty($options['block'])) {
<ide> return $out . "\n";
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function script($url, array $options = [])
<ide> if (empty($options['block'])) {
<ide> return $out . "\n";
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function scriptEnd()
<ide> $buffer = ob_get_clean();
<ide> $options = $this->_scriptBlockOptions;
<ide> $this->_scriptBlockOptions = [];
<add>
<ide> return $this->scriptBlock($buffer, $options);
<ide> }
<ide>
<ide> public function style(array $data, $oneLine = true)
<ide> if ($oneLine) {
<ide> return implode(' ', $out);
<ide> }
<add>
<ide> return implode("\n", $out);
<ide> }
<ide>
<ide> public function getCrumbs($separator = '»', $startText = false)
<ide> $out[] = $crumb[0];
<ide> }
<ide> }
<add>
<ide> return implode($separator, $out);
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function getCrumbList(array $options = [], $startText = false)
<ide> 'attrs' => $this->templater()->formatAttributes($options)
<ide> ]);
<ide> }
<add>
<ide> return $this->formatTemplate('ul', [
<ide> 'content' => $result,
<ide> 'attrs' => $this->templater()->formatAttributes($ulOptions)
<ide> protected function _prepareCrumbs($startText, $escape = true)
<ide> unset($startText['url'], $startText['text']);
<ide> array_unshift($crumbs, [$text, $url, $startText + ['escape' => $escape]]);
<ide> }
<add>
<ide> return $crumbs;
<ide> }
<ide>
<ide> public function image($path, array $options = [])
<ide> 'content' => $image
<ide> ]);
<ide> }
<add>
<ide> return $image;
<ide> }
<ide>
<ide> protected function _renderCells($line, $useCount = false)
<ide>
<ide> $cellsOut[] = $this->tableCell($cell, $cellOptions);
<ide> }
<add>
<ide> return $cellsOut;
<ide> }
<ide>
<ide> public function tag($name, $text = null, array $options = [])
<ide> } else {
<ide> $tag = 'tag';
<ide> }
<add>
<ide> return $this->formatTemplate($tag, [
<ide> 'attrs' => $this->templater()->formatAttributes($options),
<ide> 'tag' => $name,
<ide> public function div($class = null, $text = null, array $options = [])
<ide> if (!empty($class)) {
<ide> $options['class'] = $class;
<ide> }
<add>
<ide> return $this->tag('div', $text, $options);
<ide> }
<ide>
<ide> public function para($class, $text, array $options = [])
<ide> if ($text === null) {
<ide> $tag = 'parastart';
<ide> }
<add>
<ide> return $this->formatTemplate($tag, [
<ide> 'attrs' => $this->templater()->formatAttributes($options),
<ide> 'content' => $text,
<ide> public function media($path, array $options = [])
<ide> 'pathPrefix' => null,
<ide> 'text' => null
<ide> ]);
<add>
<ide> return $this->tag($tag, $text, $options);
<ide> }
<ide>
<ide> public function nestedList(array $list, array $options = [], array $itemOptions
<ide> {
<ide> $options += ['tag' => 'ul'];
<ide> $items = $this->_nestedListItem($list, $options, $itemOptions);
<add>
<ide> return $this->formatTemplate($options['tag'], [
<ide> 'attrs' => $this->templater()->formatAttributes($options, ['tag']),
<ide> 'content' => $items
<ide> protected function _nestedListItem($items, $options, $itemOptions)
<ide> ]);
<ide> $index++;
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide><path>src/View/Helper/IdGeneratorTrait.php
<ide> protected function _id($name, $val)
<ide> $check = $idSuffix . $count++;
<ide> }
<ide> $this->_idSuffixes[] = $check;
<add>
<ide> return trim($name . '-' . $check, '-');
<ide> }
<ide>
<ide> protected function _domId($value)
<ide> if (!empty($this->_idPrefix)) {
<ide> $domId = $this->_idPrefix . '-' . $domId;
<ide> }
<add>
<ide> return $domId;
<ide> }
<ide> }
<ide><path>src/View/Helper/NumberHelper.php
<ide> public function format($number, array $options = [])
<ide> {
<ide> $formatted = $this->_engine->format($number, $options);
<ide> $options += ['escape' => true];
<add>
<ide> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide> public function currency($number, $currency = null, array $options = [])
<ide> {
<ide> $formatted = $this->_engine->currency($number, $currency, $options);
<ide> $options += ['escape' => true];
<add>
<ide> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide> public function formatDelta($value, array $options = [])
<ide> {
<ide> $formatted = $this->_engine->formatDelta($value, $options);
<ide> $options += ['escape' => true];
<add>
<ide> return $options['escape'] ? h($formatted) : $formatted;
<ide> }
<ide>
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function params($model = null)
<ide> if (!isset($this->request->params['paging']) || empty($this->request->params['paging'][$model])) {
<ide> return [];
<ide> }
<add>
<ide> return $this->request->params['paging'][$model];
<ide> }
<ide>
<ide> public function param($key, $model = null)
<ide> if (!isset($params[$key])) {
<ide> return null;
<ide> }
<add>
<ide> return $params[$key];
<ide> }
<ide>
<ide> public function current($model = null)
<ide> if (isset($params['page'])) {
<ide> return $params['page'];
<ide> }
<add>
<ide> return 1;
<ide> }
<ide>
<ide> public function sortKey($model = null, array $options = [])
<ide> if (!empty($options['sort'])) {
<ide> return $options['sort'];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> public function sortDir($model = null, array $options = [])
<ide> if ($dir === 'desc') {
<ide> return 'desc';
<ide> }
<add>
<ide> return 'asc';
<ide> }
<ide>
<ide> public function prev($title = '<< Previous', array $options = [])
<ide> 'active' => 'prevActive',
<ide> 'disabled' => 'prevDisabled'
<ide> ];
<add>
<ide> return $this->_toggledLink($title, $enabled, $options, $templates);
<ide> }
<ide>
<ide> public function next($title = 'Next >>', array $options = [])
<ide> 'active' => 'nextActive',
<ide> 'disabled' => 'nextDisabled'
<ide> ];
<add>
<ide> return $this->_toggledLink($title, $enabled, $options, $templates);
<ide> }
<ide>
<ide> public function sort($key, $title = null, array $options = [])
<ide> 'text' => $options['escape'] ? h($title) : $title,
<ide> 'url' => $this->generateUrl($url, $options['model']),
<ide> ];
<add>
<ide> return $this->templater()->format($template, $vars);
<ide> }
<ide>
<ide> public function generateUrl(array $options = [], $model = null, $full = false)
<ide> ) {
<ide> $url['sort'] = $url['direction'] = null;
<ide> }
<add>
<ide> return $this->Url->build($url, $full);
<ide> }
<ide>
<ide> public function hasPage($model = null, $page = 1)
<ide> if ($paging === []) {
<ide> return false;
<ide> }
<add>
<ide> return $page <= $paging['pageCount'];
<ide> }
<ide>
<ide> public function hasPage($model = null, $page = 1)
<ide> protected function _hasPage($model, $page)
<ide> {
<ide> $params = $this->params($model);
<add>
<ide> return !empty($params) && $params[$page . 'Page'];
<ide> }
<ide>
<ide> public function defaultModel()
<ide> return null;
<ide> }
<ide> list($this->_defaultModel) = array_keys($this->request->params['paging']);
<add>
<ide> return $this->_defaultModel;
<ide> }
<ide>
<ide> public function counter($options = [])
<ide> $map += [
<ide> 'model' => strtolower(Inflector::humanize(Inflector::tableize($options['model'])))
<ide> ];
<add>
<ide> return $this->templater()->format($template, $map);
<ide> }
<ide>
<ide> protected function _getNumbersStartAndEnd($params, $options)
<ide> $start = 1;
<ide> $end = $params['page'] + ($options['modulus'] - $params['page']) + 1;
<ide> }
<add>
<ide> return [$start, $end];
<ide> }
<ide>
<ide> protected function _formatNumber($templater, $options)
<ide> 'text' => $options['text'],
<ide> 'url' => $this->generateUrl($url, $options['model']),
<ide> ];
<add>
<ide> return $templater->format('number', $vars);
<ide> }
<ide>
<ide> protected function _modulusNumbers($templater, $params, $options)
<ide>
<ide> $out .= $options['after'];
<ide> $out .= $this->_lastNumber($ellipsis, $params, $end, $options);
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _firstNumber($ellipsis, $params, $start, $options)
<ide> $out .= $ellipsis;
<ide> }
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _lastNumber($ellipsis, $params, $end, $options)
<ide> }
<ide> $out .= $this->last($offset, $options);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _numbers($templater, $params, $options)
<ide> }
<ide> }
<ide> $out .= $options['after'];
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function first($first = '<< first', array $options = [])
<ide> 'text' => $first
<ide> ]);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function last($last = 'last >>', array $options = [])
<ide> 'text' => $last
<ide> ]);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide><path>src/View/Helper/RssHelper.php
<ide> public function channel($attrib = [], $elements = [], $content = null)
<ide> }
<ide> $elems .= $this->elem($elem, $attributes, $data);
<ide> }
<add>
<ide> return $this->elem('channel', $attrib, $elems . $content, !($content === null));
<ide> }
<ide>
<ide> public function items($items, $callback = null)
<ide> for ($i = 0; $i < $c; $i++) {
<ide> $out .= $this->item([], $items[$i]);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> public function item($att = [], $elements = [])
<ide> if (!empty($elements)) {
<ide> $content = implode('', $elements);
<ide> }
<add>
<ide> return $this->elem('item', (array)$att, $content, !($content === null));
<ide> }
<ide>
<ide> public function elem($name, $attrib = [], $content = null, $endTag = true)
<ide>
<ide> $xml = $elem->saveXml();
<ide> $xml = trim(substr($xml, strpos($xml, '?>') + 2));
<add>
<ide> return $xml;
<ide> }
<ide>
<ide><path>src/View/Helper/TextHelper.php
<ide> public function autoLinkUrls($text, array $options = [])
<ide> if ($options['escape']) {
<ide> $text = h($text);
<ide> }
<add>
<ide> return $this->_linkUrls($text, $options);
<ide> }
<ide>
<ide> protected function _insertPlaceHolder($matches)
<ide> {
<ide> $key = md5($matches[0]);
<ide> $this->_placeholders[$key] = $matches[0];
<add>
<ide> return $key;
<ide> }
<ide>
<ide> protected function _linkUrls($text, $htmlOptions)
<ide> }
<ide> $replace[$hash] = $this->Html->link($link, $url, $htmlOptions);
<ide> }
<add>
<ide> return strtr($text, $replace);
<ide> }
<ide>
<ide> protected function _linkEmails($text, $options)
<ide> foreach ($this->_placeholders as $hash => $url) {
<ide> $replace[$hash] = $this->Html->link($url, 'mailto:' . $url, $options);
<ide> }
<add>
<ide> return strtr($text, $replace);
<ide> }
<ide>
<ide> public function autoLinkEmails($text, array $options = [])
<ide> if ($options['escape']) {
<ide> $text = h($text);
<ide> }
<add>
<ide> return $this->_linkEmails($text, $options);
<ide> }
<ide>
<ide> public function autoLinkEmails($text, array $options = [])
<ide> public function autoLink($text, array $options = [])
<ide> {
<ide> $text = $this->autoLinkUrls($text, $options);
<add>
<ide> return $this->autoLinkEmails($text, ['escape' => false] + $options);
<ide> }
<ide>
<ide> public function autoParagraph($text)
<ide> }
<ide> $text = preg_replace('|<p>\s*</p>|', '', $text);
<ide> }
<add>
<ide> return $text;
<ide> }
<ide>
<ide><path>src/View/Helper/TimeHelper.php
<ide> protected function _getTimezone($timezone)
<ide> if ($timezone) {
<ide> return $timezone;
<ide> }
<add>
<ide> return $this->config('outputTimezone');
<ide> }
<ide>
<ide> public function fromString($dateString, $timezone = null)
<ide> public function nice($dateString = null, $timezone = null, $locale = null)
<ide> {
<ide> $timezone = $this->_getTimezone($timezone);
<add>
<ide> return (new Time($dateString))->nice($timezone, $locale);
<ide> }
<ide>
<ide> public function toUnix($dateString, $timezone = null)
<ide> public function toAtom($dateString, $timezone = null)
<ide> {
<ide> $timezone = $this->_getTimezone($timezone) ?: date_default_timezone_get();
<add>
<ide> return (new Time($dateString))->timezone($timezone)->toAtomString();
<ide> }
<ide>
<ide> public function toAtom($dateString, $timezone = null)
<ide> public function toRss($dateString, $timezone = null)
<ide> {
<ide> $timezone = $this->_getTimezone($timezone) ?: date_default_timezone_get();
<add>
<ide> return (new Time($dateString))->timezone($timezone)->toRssString();
<ide> }
<ide>
<ide> public function timeAgoInWords($dateTime, array $options = [])
<ide> $element['tag']
<ide> );
<ide> }
<add>
<ide> return $relativeDate;
<ide> }
<ide>
<ide> public function i18nFormat($date, $format = null, $invalid = false, $timezone =
<ide>
<ide> try {
<ide> $time = new Time($date);
<add>
<ide> return $time->i18nFormat($format, $timezone);
<ide> } catch (Exception $e) {
<ide> if ($invalid === false) {
<ide> throw $e;
<ide> }
<add>
<ide> return $invalid;
<ide> }
<ide> }
<ide><path>src/View/Helper/UrlHelper.php
<ide> public function build($url = null, $full = false)
<ide> public function image($path, array $options = [])
<ide> {
<ide> $pathPrefix = Configure::read('App.imageBaseUrl');
<add>
<ide> return $this->assetUrl($path, $options + compact('pathPrefix'));
<ide> }
<ide>
<ide> public function css($path, array $options = [])
<ide> {
<ide> $pathPrefix = Configure::read('App.cssBaseUrl');
<ide> $ext = '.css';
<add>
<ide> return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
<ide> }
<ide>
<ide> public function script($path, array $options = [])
<ide> {
<ide> $pathPrefix = Configure::read('App.jsBaseUrl');
<ide> $ext = '.js';
<add>
<ide> return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
<ide> }
<ide>
<ide> public function assetUrl($path, array $options = [])
<ide> if (!empty($options['fullBase'])) {
<ide> $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
<ide> }
<add>
<ide> return $path;
<ide> }
<ide>
<ide> protected function _encodeUrl($url)
<ide> $parts = array_map('rawurldecode', explode('/', $path));
<ide> $parts = array_map('rawurlencode', $parts);
<ide> $encoded = implode('/', $parts);
<add>
<ide> return h(str_replace($path, $encoded, $url));
<ide> }
<ide>
<ide> public function assetTimestamp($path)
<ide> //@codingStandardsIgnoreEnd
<ide> }
<ide> }
<add>
<ide> return $path;
<ide> }
<ide>
<ide> public function webroot($file)
<ide> if (strpos($webPath, '//') !== false) {
<ide> return str_replace('//', '/', $webPath . $asset[1]);
<ide> }
<add>
<ide> return $webPath . $asset[1];
<ide> }
<ide>
<ide><path>src/View/HelperRegistry.php
<ide> public function __isset($helper)
<ide> } catch (Exception\MissingHelperException $exception) {
<ide> if ($this->_View->plugin) {
<ide> $this->load($this->_View->plugin . '.' . $helper);
<add>
<ide> return true;
<ide> }
<ide> }
<ide> public function __get($name)
<ide> if (isset($this->$name)) {
<ide> return $this->_loaded[$name];
<ide> }
<add>
<ide> return null;
<ide> }
<ide>
<ide> protected function _create($class, $alias, $settings)
<ide> if ($enable) {
<ide> $this->eventManager()->on($instance);
<ide> }
<add>
<ide> return $instance;
<ide> }
<ide> }
<ide><path>src/View/JsonView.php
<ide> protected function _serialize($serialize)
<ide> if (Configure::read('debug')) {
<ide> $jsonOptions = $jsonOptions | JSON_PRETTY_PRINT;
<ide> }
<add>
<ide> return json_encode($data, $jsonOptions);
<ide> }
<ide>
<ide> protected function _dataToSerialize($serialize = true)
<ide> $data[$alias] = $this->viewVars[$key];
<ide> }
<ide> }
<add>
<ide> return !empty($data) ? $data : null;
<ide> }
<ide>
<ide><path>src/View/SerializedView.php
<ide> public function render($view = null, $layout = null)
<ide> if ($result === false) {
<ide> throw new RuntimeException('Serialization of View data failed.');
<ide> }
<add>
<ide> return (string)$result;
<ide> }
<ide> if ($view !== false && $this->_getViewFileName($view)) {
<ide><path>src/View/StringTemplate.php
<ide> public function add(array $templates)
<ide> {
<ide> $this->config($templates);
<ide> $this->_compileTemplates(array_keys($templates));
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function format($name, array $data)
<ide> }
<ide> $replace[] = $replacement;
<ide> }
<add>
<ide> return vsprintf($template, $replace);
<ide> }
<ide>
<ide> public function formatAttributes($options, $exclude = null)
<ide> }
<ide> }
<ide> $out = trim(implode(' ', $attributes));
<add>
<ide> return $out ? $insertBefore . $out : '';
<ide> }
<ide>
<ide> protected function _formatAttribute($key, $value, $escape = true)
<ide> if ($isMinimized) {
<ide> return '';
<ide> }
<add>
<ide> return $key . '="' . ($escape ? h($value) : $value) . '"';
<ide> }
<ide> }
<ide><path>src/View/StringTemplateTrait.php
<ide> public function templates($templates = null)
<ide> }
<ide>
<ide> $this->templater()->add($templates);
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function templater()
<ide> }
<ide> }
<ide> }
<add>
<ide> return $this->_templater;
<ide> }
<ide> }
<ide><path>src/View/View.php
<ide> public function cache(callable $block, array $options = [])
<ide> $result = ob_get_clean();
<ide>
<ide> Cache::write($options['key'], $result, $options['config']);
<add>
<ide> return $result;
<ide> }
<ide>
<ide> public function render($view = null, $layout = null)
<ide> }
<ide>
<ide> $this->hasRendered = true;
<add>
<ide> return $this->Blocks->get('content');
<ide> }
<ide>
<ide> public function renderLayout($content, $layout = null)
<ide> $this->Blocks->set('content', $this->_render($layoutFileName));
<ide>
<ide> $this->dispatchEvent('View.afterLayout', [$layoutFileName]);
<add>
<ide> return $this->Blocks->get('content');
<ide> }
<ide>
<ide> public function get($var, $default = null)
<ide> if (!isset($this->viewVars[$var])) {
<ide> return $default;
<ide> }
<add>
<ide> return $this->viewVars[$var];
<ide> }
<ide>
<ide> public function uuid($object, $url)
<ide> $c++;
<ide> }
<ide> $this->uuids[] = $hash;
<add>
<ide> return $hash;
<ide> }
<ide>
<ide> public function __get($name)
<ide> $registry = $this->helpers();
<ide> if (isset($registry->{$name})) {
<ide> $this->{$name} = $registry->{$name};
<add>
<ide> return $registry->{$name};
<ide> }
<add>
<ide> return $this->{$name};
<ide> }
<ide>
<ide> public function __set($name, $value)
<ide> {
<ide> if ($name === 'view') {
<ide> $this->template = $value;
<add>
<ide> return;
<ide> }
<ide> if ($name === 'viewPath') {
<ide> $this->templatePath = $value;
<add>
<ide> return;
<ide> }
<ide>
<ide> protected function _render($viewFile, $data = [])
<ide> $this->Blocks->active()
<ide> ));
<ide> }
<add>
<ide> return $content;
<ide> }
<ide>
<ide> protected function _evaluate($viewFile, $dataForView)
<ide> include $this->__viewFile;
<ide>
<ide> unset($this->__viewFile);
<add>
<ide> return ob_get_clean();
<ide> }
<ide>
<ide> public function helpers()
<ide> if ($this->_helpers === null) {
<ide> $this->_helpers = new HelperRegistry($this);
<ide> }
<add>
<ide> return $this->_helpers;
<ide> }
<ide>
<ide> public function loadHelper($name, array $config = [])
<ide> {
<ide> list(, $class) = pluginSplit($name);
<ide> $helpers = $this->helpers();
<add>
<ide> return $this->{$class} = $helpers->load($name, $config);
<ide> }
<ide>
<ide> protected function _checkFilePath($file, $path)
<ide> $file
<ide> ));
<ide> }
<add>
<ide> return $absolute;
<ide> }
<ide>
<ide> public function pluginSplit($name, $fallback = true)
<ide> if (isset($this->plugin) && !$plugin && $fallback) {
<ide> $plugin = $this->plugin;
<ide> }
<add>
<ide> return [$plugin, $name];
<ide> }
<ide>
<ide> protected function _getElementFileName($name)
<ide> }
<ide> }
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide> protected function _paths($plugin = null, $cached = true)
<ide> if ($plugin !== null) {
<ide> return $this->_pathsForPlugin[$plugin] = $paths;
<ide> }
<add>
<ide> return $this->_paths = $paths;
<ide> }
<ide>
<ide> protected function _elementCache($name, $data, $options)
<ide> $config = $options['cache'] + $defaults;
<ide> }
<ide> $config['key'] = 'element_' . $config['key'];
<add>
<ide> return $config;
<ide> }
<ide>
<ide><path>src/View/ViewBlock.php
<ide> public function end()
<ide> if ($this->_discardActiveBufferOnEnd) {
<ide> $this->_discardActiveBufferOnEnd = false;
<ide> ob_end_clean();
<add>
<ide> return;
<ide> }
<ide> if (!empty($this->_active)) {
<ide> public function concat($name, $value = null, $mode = ViewBlock::APPEND)
<ide> {
<ide> if ($value === null) {
<ide> $this->start($name, $mode);
<add>
<ide> return;
<ide> }
<ide>
<ide> public function get($name, $default = '')
<ide> if (!isset($this->_blocks[$name])) {
<ide> return $default;
<ide> }
<add>
<ide> return $this->_blocks[$name];
<ide> }
<ide>
<ide> public function keys()
<ide> public function active()
<ide> {
<ide> end($this->_active);
<add>
<ide> return key($this->_active);
<ide> }
<ide>
<ide><path>src/View/ViewBuilder.php
<ide> public function templatePath($path = null)
<ide> }
<ide>
<ide> $this->_templatePath = $path;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function layoutPath($path = null)
<ide> }
<ide>
<ide> $this->_layoutPath = $path;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function autoLayout($autoLayout = null)
<ide> }
<ide>
<ide> $this->_autoLayout = (bool)$autoLayout;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function plugin($name = null)
<ide> }
<ide>
<ide> $this->_plugin = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function helpers(array $helpers = null, $merge = true)
<ide> $helpers = array_merge($this->_helpers, $helpers);
<ide> }
<ide> $this->_helpers = $helpers;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function theme($theme = null)
<ide> }
<ide>
<ide> $this->_theme = $theme;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function template($name = null)
<ide> }
<ide>
<ide> $this->_template = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function layout($name = null)
<ide> }
<ide>
<ide> $this->_layout = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function options(array $options = null, $merge = true)
<ide> $options = array_merge($this->_options, $options);
<ide> }
<ide> $this->_options = $options;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function name($name = null)
<ide> return $this->_name;
<ide> }
<ide> $this->_name = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function className($name = null)
<ide> return $this->_className;
<ide> }
<ide> $this->_className = $name;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function build($vars = [], Request $request = null, Response $response =
<ide> 'viewVars' => $vars,
<ide> ];
<ide> $data += $this->_options;
<add>
<ide> return new $className($request, $response, $events, $data);
<ide> }
<ide>
<ide> public function createFromArray($config)
<ide> public function serialize()
<ide> {
<ide> $array = $this->jsonSerialize();
<add>
<ide> return serialize($array);
<ide> }
<ide>
<ide><path>src/View/ViewVarsTrait.php
<ide> public function viewBuilder()
<ide> if (!isset($this->_viewBuilder)) {
<ide> $this->_viewBuilder = new ViewBuilder();
<ide> }
<add>
<ide> return $this->_viewBuilder;
<ide> }
<ide>
<ide> public function createView($viewClass = null)
<ide> }
<ide> }
<ide> $builder->options($viewOptions);
<add>
<ide> return $builder->build(
<ide> $this->viewVars,
<ide> isset($this->request) ? $this->request : null,
<ide> public function set($name, $value = null)
<ide> $data = [$name => $value];
<ide> }
<ide> $this->viewVars = $data + $this->viewVars;
<add>
<ide> return $this;
<ide> }
<ide>
<ide><path>src/View/Widget/BasicWidget.php
<ide> public function secureFields(array $data)
<ide> if (!isset($data['name']) || $data['name'] === '') {
<ide> return [];
<ide> }
<add>
<ide> return [$data['name']];
<ide> }
<ide> }
<ide><path>src/View/Widget/ButtonWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> 'escape' => false,
<ide> 'templateVars' => []
<ide> ];
<add>
<ide> return $this->_templates->format('button', [
<ide> 'text' => $data['escape'] ? h($data['text']) : $data['text'],
<ide> 'templateVars' => $data['templateVars'],
<ide><path>src/View/Widget/CheckboxWidget.php
<ide> protected function _isChecked($data)
<ide> if (array_key_exists('checked', $data)) {
<ide> return (bool)$data['checked'];
<ide> }
<add>
<ide> return (string)$data['val'] === (string)$data['value'];
<ide> }
<ide> }
<ide><path>src/View/Widget/DateTimeWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> }
<ide> unset($data['name'], $data['empty'], $data['disabled'], $data['val']);
<ide> $templateOptions['attrs'] = $this->_templates->formatAttributes($data);
<add>
<ide> return $this->_templates->format('dateWidget', $templateOptions);
<ide> }
<ide>
<ide> protected function _adjustValue($value, $options)
<ide> default:
<ide> $changeValue = round($changeValue);
<ide> }
<add>
<ide> return ($changeValue * $options['interval']) - $value;
<ide> }
<ide>
<ide> protected function _yearSelect($options, $context)
<ide> $options['options'] = array_reverse($options['options'], true);
<ide> }
<ide> unset($options['start'], $options['end'], $options['order']);
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _monthSelect($options, $context)
<ide> }
<ide>
<ide> unset($options['leadingZeroKey'], $options['leadingZeroValue'], $options['names']);
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _daySelect($options, $context)
<ide> $options['options'] = $this->_generateNumbers(1, 31, $options);
<ide>
<ide> unset($options['names'], $options['leadingZeroKey'], $options['leadingZeroValue']);
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _hourSelect($options, $context)
<ide> $options['leadingZeroKey'],
<ide> $options['leadingZeroValue']
<ide> );
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _minuteSelect($options, $context)
<ide> $options['interval'],
<ide> $options['round']
<ide> );
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _secondSelect($options, $context)
<ide> ];
<ide>
<ide> unset($options['leadingZeroKey'], $options['leadingZeroValue']);
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _meridianSelect($options, $context)
<ide> 'options' => ['am' => 'am', 'pm' => 'pm'],
<ide> 'templateVars' => [],
<ide> ];
<add>
<ide> return $this->_select->render($options, $context);
<ide> }
<ide>
<ide> protected function _generateNumbers($start, $end, $options = [])
<ide> $numbers[$key] = $value;
<ide> $i += $options['interval'];
<ide> }
<add>
<ide> return $numbers;
<ide> }
<ide>
<ide> public function secureFields(array $data)
<ide>
<ide> $fields[] = $data['name'] . '[' . $select . ']';
<ide> }
<add>
<ide> return $fields;
<ide> }
<ide> }
<ide><path>src/View/Widget/FileWidget.php
<ide> public function secureFields(array $data)
<ide> foreach (['name', 'type', 'tmp_name', 'error', 'size'] as $suffix) {
<ide> $fields[] = $data['name'] . '[' . $suffix . ']';
<ide> }
<add>
<ide> return $fields;
<ide> }
<ide> }
<ide><path>src/View/Widget/MultiCheckboxWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> ];
<ide> $this->_idPrefix = $data['idPrefix'];
<ide> $this->_clearIds();
<add>
<ide> return implode('', $this->_renderInputs($data, $context));
<ide> }
<ide>
<ide> protected function _renderInputs($data, $context)
<ide> }
<ide> $out[] = $this->_renderInput($checkbox, $context);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _isSelected($key, $selected)
<ide> return (string)$key === (string)$selected;
<ide> }
<ide> $strict = !is_numeric($key);
<add>
<ide> return in_array((string)$key, $selected, $strict);
<ide> }
<ide>
<ide> protected function _isDisabled($key, $disabled)
<ide> return true;
<ide> }
<ide> $strict = !is_numeric($key);
<add>
<ide> return in_array((string)$key, $disabled, $strict);
<ide> }
<ide>
<ide><path>src/View/Widget/RadioWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> foreach ($options as $val => $text) {
<ide> $opts[] = $this->_renderInput($val, $text, $data, $context);
<ide> }
<add>
<ide> return implode('', $opts);
<ide> }
<ide>
<ide> protected function _isDisabled($radio, $disabled)
<ide> return true;
<ide> }
<ide> $isNumeric = is_numeric($radio['value']);
<add>
<ide> return (!is_array($disabled) || in_array((string)$radio['value'], $disabled, !$isNumeric));
<ide> }
<ide>
<ide> protected function _renderLabel($radio, $label, $input, $context, $escape)
<ide> 'templateVars' => $radio['templateVars'],
<ide> 'input' => $input,
<ide> ];
<add>
<ide> return $this->_label->render($labelAttrs, $context);
<ide> }
<ide>
<ide><path>src/View/Widget/SelectBoxWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> unset($data['multiple']);
<ide> }
<ide> $attrs = $this->_templates->formatAttributes($data);
<add>
<ide> return $this->_templates->format($template, [
<ide> 'name' => $name,
<ide> 'templateVars' => $data['templateVars'],
<ide> protected function _renderContent($data)
<ide> $disabled = $data['disabled'];
<ide> }
<ide> $templateVars = $data['templateVars'];
<add>
<ide> return $this->_renderOptions($options, $disabled, $selected, $templateVars, $data['escape']);
<ide> }
<ide>
<ide> protected function _emptyValue($value)
<ide> if (is_array($value)) {
<ide> return $value;
<ide> }
<add>
<ide> return [];
<ide> }
<ide>
<ide> protected function _renderOptions($options, $disabled, $selected, $templateVars,
<ide> 'attrs' => $this->_templates->formatAttributes($optAttrs, ['text', 'value']),
<ide> ]);
<ide> }
<add>
<ide> return $out;
<ide> }
<ide>
<ide> protected function _isSelected($key, $selected)
<ide> $isArray = is_array($selected);
<ide> if (!$isArray) {
<ide> $selected = $selected === false ? '0' : $selected;
<add>
<ide> return (string)$key === (string)$selected;
<ide> }
<ide> $strict = !is_numeric($key);
<add>
<ide> return in_array((string)$key, $selected, $strict);
<ide> }
<ide>
<ide> protected function _isDisabled($key, $disabled)
<ide> return false;
<ide> }
<ide> $strict = !is_numeric($key);
<add>
<ide> return in_array((string)$key, $disabled, $strict);
<ide> }
<ide> }
<ide><path>src/View/Widget/TextareaWidget.php
<ide> public function render(array $data, ContextInterface $context)
<ide> 'rows' => 5,
<ide> 'templateVars' => []
<ide> ];
<add>
<ide> return $this->_templates->format('textarea', [
<ide> 'name' => $data['name'],
<ide> 'value' => $data['escape'] ? h($data['val']) : $data['val'],
<ide><path>src/View/Widget/WidgetRegistry.php
<ide> public function get($name)
<ide> $name = '_default';
<ide> }
<ide> $this->_widgets[$name] = $this->_resolveWidget($this->_widgets[$name]);
<add>
<ide> return $this->_widgets[$name];
<ide> }
<ide>
<ide> protected function _resolveWidget($widget)
<ide> if (!($instance instanceof WidgetInterface)) {
<ide> throw new RuntimeException(sprintf('"%s" does not implement the WidgetInterface', $className));
<ide> }
<add>
<ide> return $instance;
<ide> }
<ide> }
<ide><path>src/View/XmlView.php
<ide> protected function _serialize($serialize)
<ide> if (isset($options['return']) && strtolower($options['return']) === 'domdocument') {
<ide> return Xml::fromArray($data, $options)->saveXML();
<ide> }
<add>
<ide> return Xml::fromArray($data, $options)->asXML();
<ide> }
<ide> }
<ide><path>src/basics.php
<ide> function json_last_error_msg()
<ide> JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
<ide> ];
<ide> $error = json_last_error();
<add>
<ide> return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
<ide> }
<ide>
<ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testReject()
<ide> $collection = new Collection($items);
<ide> $result = $collection->reject(function ($v, $k, $items) use ($collection) {
<ide> $this->assertSame($collection->getInnerIterator(), $items);
<add>
<ide> return $v > 2;
<ide> });
<ide> $this->assertEquals(['a' => 1, 'b' => 2], iterator_to_array($result));
<ide> public function testMap()
<ide> $collection = new Collection($items);
<ide> $map = $collection->map(function ($v, $k, $it) use ($collection) {
<ide> $this->assertSame($collection->getInnerIterator(), $it);
<add>
<ide> return $v * $v;
<ide> });
<ide> $this->assertInstanceOf('Cake\Collection\Iterator\ReplaceIterator', $map);
<ide> public function testThroughReturnArray()
<ide> $items = [1, 2, 3];
<ide> $collection = (new Collection($items))->through(function ($collection) {
<ide> $list = $collection->toList();
<add>
<ide> return array_merge($list, $list);
<ide> });
<ide>
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testAfterIdentifyForStatelessAuthentication()
<ide> EventManager::instance()->on('Auth.afterIdentify', function ($event) {
<ide> $user = $event->data[0];
<ide> $user['from_callback'] = true;
<add>
<ide> return $user;
<ide> });
<ide>
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> protected function _oldImplode(array $array)
<ide> foreach ($array as $key => $value) {
<ide> $string .= ',' . $key . '|' . $value;
<ide> }
<add>
<ide> return substr($string, 1);
<ide> }
<ide>
<ide> protected function _encrypt($value)
<ide> if (is_array($value)) {
<ide> $value = $this->_implode($value);
<ide> }
<add>
<ide> return "Q2FrZQ==." . base64_encode(Security::encrypt($value, $this->Cookie->config('key')));
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testPaginateCustomFind()
<ide> foreach ($result as $record) {
<ide> $ids[] = $record->title;
<ide> }
<add>
<ide> return $ids;
<ide> };
<ide>
<ide> protected function _getMockFindQuery($table = null)
<ide> ->will($this->returnValue(2));
<ide>
<ide> $query->repository($table);
<add>
<ide> return $query;
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function validatePost($expectedException = null, $expectedExceptionMessag
<ide> } catch (SecurityException $ex) {
<ide> $this->assertInstanceOf('Cake\\Controller\\Exception\\' . $expectedException, $ex);
<ide> $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
<add>
<ide> return false;
<ide> }
<ide> }
<ide><path>tests/TestCase/Core/AppTest.php
<ide> public function testClassname($class, $type, $suffix = '', $existsInBase = false
<ide> if ($checkCake) {
<ide> return (bool)$expected;
<ide> }
<add>
<ide> return false;
<ide> };
<ide> $return = TestApp::classname($class, $type, $suffix);
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public static function parseDsn($config = null)
<ide> }
<ide>
<ide> unset($config['path']);
<add>
<ide> return $config;
<ide> }
<ide>
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function getMockFormDriver()
<ide> $driver->expects($this->once())
<ide> ->method('enabled')
<ide> ->will($this->returnValue(true));
<add>
<ide> return $driver;
<ide> }
<ide>
<ide> public function testTransactionalSuccess()
<ide> $connection->expects($this->at(1))->method('commit');
<ide> $result = $connection->transactional(function ($conn) use ($connection) {
<ide> $this->assertSame($connection, $conn);
<add>
<ide> return 'thing';
<ide> });
<ide> $this->assertEquals('thing', $result);
<ide> public function testTransactionalFail()
<ide> $connection->expects($this->never())->method('commit');
<ide> $result = $connection->transactional(function ($conn) use ($connection) {
<ide> $this->assertSame($connection, $conn);
<add>
<ide> return false;
<ide> });
<ide> $this->assertFalse($result);
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testSelectClosure()
<ide> $query = new Query($this->connection);
<ide> $result = $query->select(function ($q) use ($query) {
<ide> $this->assertSame($query, $q);
<add>
<ide> return ['1 + 2', '1 + 5'];
<ide> })->execute();
<ide> $this->assertEquals([3, 6], $result->fetch());
<ide> public function testSelectJoinWithCallback()
<ide> ->innerJoin(['c' => 'comments'], function ($exp, $q) use ($query, $types) {
<ide> $this->assertSame($q, $query);
<ide> $exp->add(['created <' => new \DateTime('2007-03-18 10:45:23')], $types);
<add>
<ide> return $exp;
<ide> })
<ide> ->execute();
<ide> public function testSelectJoinWithCallback()
<ide> ->innerJoin('comments', function ($exp, $q) use ($query, $types) {
<ide> $this->assertSame($q, $query);
<ide> $exp->add(['created >' => new \DateTime('2007-03-18 10:45:23')], $types);
<add>
<ide> return $exp;
<ide> })
<ide> ->execute();
<ide> public function testSelectWhereUsingExpressionInField()
<ide> ->where(function ($exp) {
<ide> $field = clone $exp;
<ide> $field->add('SELECT min(id) FROM comments');
<add>
<ide> return $exp
<ide> ->eq($field, 100, 'integer');
<ide> })
<ide> public function testWhereWithBetweenComplex()
<ide> ->where(function ($exp) {
<ide> $from = new \DateTime('2007-03-18 10:51:00');
<ide> $to = new \DateTime('2007-03-18 10:54:00');
<add>
<ide> return $exp->between('created', $from, $to, 'datetime');
<ide> })
<ide> ->execute();
<ide> public function testWhereWithBetweenWithExpressionField()
<ide> ->from('comments')
<ide> ->where(function ($exp, $q) {
<ide> $field = $q->func()->coalesce([new IdentifierExpression('id'), 1 => 'literal']);
<add>
<ide> return $exp->between($field, 5, 6, 'integer');
<ide> })
<ide> ->execute();
<ide> public function testWhereWithBetweenWithExpressionParts()
<ide> ->where(function ($exp, $q) {
<ide> $from = $q->newExpr("'2007-03-18 10:51:00'");
<ide> $to = $q->newExpr("'2007-03-18 10:54:00'");
<add>
<ide> return $exp->between('created', $from, $to);
<ide> })
<ide> ->execute();
<ide> public function testSelectExpressionComposition()
<ide> ->from('comments')
<ide> ->where(function ($exp) {
<ide> $and = $exp->and_(['id' => 2, 'id >' => 1]);
<add>
<ide> return $exp->add($and);
<ide> })
<ide> ->execute();
<ide> public function testSelectExpressionComposition()
<ide> ->from('comments')
<ide> ->where(function ($exp) {
<ide> $and = $exp->and_(['id' => 2, 'id <' => 2]);
<add>
<ide> return $exp->add($and);
<ide> })
<ide> ->execute();
<ide> public function testSelectExpressionComposition()
<ide> $and = $exp->and_(function ($and) {
<ide> return $and->eq('id', 1)->gt('id', 0);
<ide> });
<add>
<ide> return $exp->add($and);
<ide> })
<ide> ->execute();
<ide> public function testSelectExpressionComposition()
<ide> ->where(function ($exp) {
<ide> $or = $exp->or_(['id' => 1]);
<ide> $and = $exp->and_(['id >' => 2, 'id <' => 4]);
<add>
<ide> return $or->add($and);
<ide> })
<ide> ->execute();
<ide> public function testSelectExpressionComposition()
<ide> $or = $exp->or_(function ($or) {
<ide> return $or->eq('id', 1)->eq('id', 2);
<ide> });
<add>
<ide> return $or;
<ide> })
<ide> ->execute();
<ide> public function testDecorateResults()
<ide> ->order(['id' => 'ASC'])
<ide> ->decorateResults(function ($row) {
<ide> $row['modified_id'] = $row['id'] + 1;
<add>
<ide> return $row;
<ide> })
<ide> ->execute();
<ide> public function testDecorateResults()
<ide>
<ide> $result = $query->decorateResults(function ($row) {
<ide> $row['modified_id']--;
<add>
<ide> return $row;
<ide> })->execute();
<ide>
<ide> public function testDecorateResults()
<ide> $result = $query
<ide> ->decorateResults(function ($row) {
<ide> $row['foo'] = 'bar';
<add>
<ide> return $row;
<ide> }, true)
<ide> ->execute();
<ide> public function testBetweenExpressionAndTypeMap()
<ide> ->where(function ($expr) {
<ide> $from = new \DateTime('2007-03-18 10:45:00');
<ide> $to = new \DateTime('2007-03-18 10:48:00');
<add>
<ide> return $expr->between('created', $from, $to);
<ide> });
<ide> $this->assertCount(2, $query->execute()->fetchAll());
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> return "'$value'";
<ide> }));
<ide> $driver->connection($mock);
<add>
<ide> return $driver;
<ide> }
<ide> }
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> return "'$value'";
<ide> }));
<ide> $driver->connection($mock);
<add>
<ide> return $driver;
<ide> }
<ide> }
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> return '"' . $value . '"';
<ide> }));
<ide> $driver->connection($mock);
<add>
<ide> return $driver;
<ide> }
<ide> }
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> return "'$value'";
<ide> }));
<ide> $driver->connection($mock);
<add>
<ide> return $driver;
<ide> }
<ide> }
<ide><path>tests/TestCase/DatabaseSuite.php
<ide> public static function suite()
<ide> $suite->addTestFile(__DIR__ . DS . 'Database' . DS . 'ConnectionTest.php');
<ide> $suite->addTestDirectoryRecursive(__DIR__ . DS . 'Database');
<ide> $suite->addTestDirectoryRecursive(__DIR__ . DS . 'ORM');
<add>
<ide> return $suite;
<ide> }
<ide>
<ide> public function run(PHPUnit_Framework_TestResult $result = null)
<ide> $permutation();
<ide> $result = parent::run($result);
<ide> }
<add>
<ide> return $result;
<ide> }
<ide> }
<ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php
<ide> public function testConfigWithCallable()
<ide> $connection = new FakeConnection;
<ide> $callable = function ($alias) use ($connection) {
<ide> $this->assertEquals('test_variant', $alias);
<add>
<ide> return $connection;
<ide> };
<ide>
<ide><path>tests/TestCase/Datasource/ModelAwareTraitTest.php
<ide> public function testModelFactory()
<ide> $stub->modelFactory('Test', function ($name) {
<ide> $mock = new \StdClass();
<ide> $mock->name = $name;
<add>
<ide> return $mock;
<ide> });
<ide>
<ide> public function testModelType()
<ide> $stub->modelFactory('Test', function ($name) {
<ide> $mock = new \StdClass();
<ide> $mock->name = $name;
<add>
<ide> return $mock;
<ide> });
<ide> $stub->modelType('Test');
<ide><path>tests/TestCase/Datasource/QueryCacherTest.php
<ide> public function testFetchFunctionKey()
<ide>
<ide> $cacher = new QueryCacher(function ($q) use ($query) {
<ide> $this->assertSame($query, $q);
<add>
<ide> return 'my_key';
<ide> }, 'queryCache');
<ide>
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public function beforeRender(Event $event)
<ide> public function index()
<ide> {
<ide> $this->autoRender = false;
<add>
<ide> return 'what up';
<ide> }
<ide> }
<ide> protected function _mockResponse($error)
<ide> $error->controller->response = $this->getMockBuilder('Cake\Network\Response')
<ide> ->setMethods(['_sendHeader'])
<ide> ->getMock();
<add>
<ide> return $error;
<ide> }
<ide>
<ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> protected function _getTmpFile($paintSkip = true)
<ide> $message = sprintf('[FileTest] Skipping %s because "%s" not writeable!', $caller, $shortPath);
<ide> $this->markTestSkipped($message);
<ide> }
<add>
<ide> return false;
<ide> }
<ide>
<ide><path>tests/TestCase/I18n/I18nTest.php
<ide> public function testCreateCustomTranslationPackage()
<ide> $package->setMessages([
<ide> 'Cow' => 'Le moo'
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testGetTranslatorByDefaultLocale()
<ide> $package->setMessages([
<ide> 'Cow' => 'Le moo'
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testBasicDomainFunction()
<ide> 'The {0} is tasty' => 'The {0} is delicious',
<ide> 'Average price {0}' => 'Price Average {0}',
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide> $this->assertEquals('Le moo', __d('custom', 'Cow'));
<ide> public function testBasicDomainPluralFunction()
<ide> 'Les Moos'
<ide> ]
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide> $this->assertEquals('Le Moo', __dn('custom', 'Cow', 'Cows', 1));
<ide> public function testBasicContextFunction()
<ide> ]
<ide> ]
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testPluralContextFunction()
<ide> ]
<ide> ]
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide> $this->assertEquals('The letters A and B', __xn('character', 'letter', 'letters', 2, ['A', 'B']));
<ide> public function testDomainContextFunction()
<ide> ]
<ide> ]
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testDomainPluralContextFunction()
<ide> ]
<ide> ]
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide> $this->assertEquals(
<ide> public function testFallbackTranslator()
<ide> $package->setMessages([
<ide> 'Dog' => 'Le bark'
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testFallbackTranslator()
<ide> $package->setMessages([
<ide> 'Cow' => 'Le moo'
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testFallbackTranslatorDisabled()
<ide> I18n::translator('default', 'fr_FR', function () {
<ide> $package = new Package('default');
<ide> $package->setMessages(['Dog' => 'Le bark']);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> I18n::translator('custom', 'fr_FR', function () {
<ide> $package = new Package('default');
<ide> $package->setMessages(['Cow' => 'Le moo']);
<add>
<ide> return $package;
<ide> });
<ide>
<ide> public function testFallbackTranslatorWithFactory()
<ide> $package->setMessages([
<ide> 'Dog' => 'Le bark'
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide> I18n::config('custom', function ($name, $locale) {
<ide> public function testFallbackTranslatorWithFactory()
<ide> $package->setMessages([
<ide> 'Cow' => 'Le moo',
<ide> ]);
<add>
<ide> return $package;
<ide> });
<ide>
<ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php
<ide> public function testParseContextOnSomeMessages()
<ide> I18n::translator('default', 'en_US', function () use ($messages) {
<ide> $package = new Package('default');
<ide> $package->setMessages($messages);
<add>
<ide> return $package;
<ide> });
<ide> $this->assertTextEquals('En cours', $messages['Pending']);
<ide><path>tests/TestCase/Log/LogTest.php
<ide> public function testCreateLoggerWithCallable()
<ide> $instance = new FileLog;
<ide> Log::config('default', function ($alias) use ($instance) {
<ide> $this->assertEquals('default', $alias);
<add>
<ide> return $instance;
<ide> });
<ide> $this->assertSame($instance, Log::engine('default')); | 300 |
Python | Python | improve a number of error messages in keras layers | fdf91ec03325eb2900d87ccaf572815968779404 | <ide><path>keras/distribute/keras_stateful_lstm_model_correctness_test.py
<ide> def disabled_test_stateful_lstm_model_correctness(
<ide> def test_incorrectly_use_multiple_cores_for_stateful_lstm_model(
<ide> self, distribution, use_numpy, use_validation_data):
<ide> with self.assertRaisesRegex(
<del> ValueError, 'RNNs with stateful=True not yet supported with '
<del> 'tf.distribute.Strategy.'):
<add> ValueError, 'not yet supported with tf.distribute.Strategy'):
<ide> self.run_correctness_test(
<ide> distribution,
<ide> use_numpy,
<ide><path>keras/layers/convolutional_recurrent.py
<ide> def __init__(self,
<ide> unroll=False,
<ide> **kwargs):
<ide> if unroll:
<del> raise TypeError('Unrolling isn\'t possible with convolutional RNNs.')
<add> raise TypeError(
<add> 'Unrolling is not possible with convolutional RNNs. '
<add> f'Received: unroll={unroll}')
<ide> if isinstance(cell, (list, tuple)):
<ide> # The StackedConvRNN3DCells isn't implemented yet.
<ide> raise TypeError('It is not possible at the moment to'
<del> 'stack convolutional cells.')
<add> 'stack convolutional cells. Only pass a single cell '
<add> 'instance as the `cell` argument. Received: '
<add> f'cell={cell}')
<ide> super(ConvRNN, self).__init__(cell, return_sequences, return_state,
<ide> go_backwards, stateful, unroll, **kwargs)
<ide> self.rank = rank
<ide> def build(self, input_shape):
<ide> ch_dim = self.rank + 1
<ide> if [spec.shape[ch_dim] for spec in self.state_spec] != state_size:
<ide> raise ValueError(
<del> 'An initial_state was passed that is not compatible with '
<del> '`cell.state_size`. Received `state_spec`={}; '
<del> 'However `cell.state_size` is '
<del> '{}'.format([spec.shape for spec in self.state_spec],
<del> self.cell.state_size))
<add> 'An `initial_state` was passed that is not compatible with '
<add> '`cell.state_size`. Received state shapes '
<add> f'{[spec.shape for spec in self.state_spec]}. '
<add> f'However `cell.state_size` is {self.cell.state_size}')
<ide> else:
<ide> img_dims = tuple((None for _ in range(self.rank)))
<ide> if self.cell.data_format == 'channels_first':
<ide> def call(self,
<ide>
<ide> if constants:
<ide> if not generic_utils.has_arg(self.cell.call, 'constants'):
<del> raise ValueError('RNN cell does not support constants')
<add> raise ValueError(
<add> f'RNN cell {self.cell} does not support constants. '
<add> f'Received: constants={constants}')
<ide>
<ide> def step(inputs, states):
<ide> constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type
<ide> def get_tuple_shape(nb_channels):
<ide> elif self.cell.data_format == 'channels_last':
<ide> result[self.rank + 1] = nb_channels
<ide> else:
<del> raise KeyError
<add> raise KeyError(
<add> 'Cell data format must be one of '
<add> '{"channels_first", "channels_last"}. Received: '
<add> f'cell.data_format={self.cell.data_format}')
<ide> return tuple(result)
<ide>
<ide> # initialize state if None
<ide> def get_tuple_shape(nb_channels):
<ide> if not isinstance(states, (list, tuple)):
<ide> states = [states]
<ide> if len(states) != len(self.states):
<del> raise ValueError('Layer ' + self.name + ' expects ' +
<del> str(len(self.states)) + ' states, ' +
<del> 'but it received ' + str(len(states)) +
<del> ' state values. Input received: ' + str(states))
<add> raise ValueError(
<add> f'Layer {self.name} expects {len(self.states)} states, '
<add> f'but it received {len(states)} state values. '
<add> f'States received: {states}')
<ide> for index, (value, state) in enumerate(zip(states, self.states)):
<ide> if hasattr(self.cell.state_size, '__len__'):
<ide> dim = self.cell.state_size[index]
<ide> else:
<ide> dim = self.cell.state_size
<ide> if value.shape != get_tuple_shape(dim):
<del> raise ValueError('State ' + str(index) +
<del> ' is incompatible with layer ' +
<del> self.name + ': expected shape=' +
<del> str(get_tuple_shape(dim)) +
<del> ', found shape=' + str(value.shape))
<del> # TODO(anjalisridhar): consider batch calls to `set_value`.
<add> raise ValueError(
<add> f'State {index} is incompatible with layer {self.name}: '
<add> f'expected shape={get_tuple_shape(dim)}, '
<add> f'found shape={value.shape}')
<ide> backend.set_value(state, value)
<ide>
<ide>
<ide> def __init__(self,
<ide> super(ConvLSTMCell, self).__init__(**kwargs)
<ide> self.rank = rank
<ide> if self.rank > 3:
<del> raise ValueError('Rank ' + str(self.rank) +
<del> ' convolutions not currently implemented.')
<add> raise ValueError(f'Rank {rank} convolutions are not currently '
<add> f'implemented. Received: rank={rank}')
<ide> self.filters = filters
<ide> self.kernel_size = conv_utils.normalize_tuple(kernel_size, self.rank,
<ide> 'kernel_size')
<ide> def build(self, input_shape):
<ide> else:
<ide> channel_axis = -1
<ide> if input_shape[channel_axis] is None:
<del> raise ValueError('The channel dimension of the inputs '
<del> 'should be defined. Found `None`.')
<add> raise ValueError(
<add> 'The channel dimension of the inputs (last axis) should be defined. '
<add> f'Found None. Full input shape received: input_shape={input_shape}')
<ide> input_dim = input_shape[channel_axis]
<ide> self.kernel_shape = self.kernel_size + (input_dim, self.filters * 4)
<ide> recurrent_kernel_shape = self.kernel_size + (self.filters, self.filters * 4)
<ide><path>keras/layers/einsum_dense.py
<ide> def compute_output_shape(self, _):
<ide>
<ide> def get_config(self):
<ide> config = {
<del> "output_shape":
<del> self.partial_output_shape,
<del> "equation":
<del> self.equation,
<del> "activation":
<del> activations.serialize(self.activation),
<del> "bias_axes":
<del> self.bias_axes,
<del> "kernel_initializer":
<del> initializers.serialize(self.kernel_initializer),
<del> "bias_initializer":
<del> initializers.serialize(self.bias_initializer),
<del> "kernel_regularizer":
<del> regularizers.serialize(self.kernel_regularizer),
<del> "bias_regularizer":
<del> regularizers.serialize(self.bias_regularizer),
<add> "output_shape": self.partial_output_shape,
<add> "equation": self.equation,
<add> "activation": activations.serialize(self.activation),
<add> "bias_axes": self.bias_axes,
<add> "kernel_initializer": initializers.serialize(self.kernel_initializer),
<add> "bias_initializer": initializers.serialize(self.bias_initializer),
<add> "kernel_regularizer": regularizers.serialize(self.kernel_regularizer),
<add> "bias_regularizer": regularizers.serialize(self.bias_regularizer),
<ide> "activity_regularizer":
<ide> regularizers.serialize(self.activity_regularizer),
<del> "kernel_constraint":
<del> constraints.serialize(self.kernel_constraint),
<del> "bias_constraint":
<del> constraints.serialize(self.bias_constraint),
<add> "kernel_constraint": constraints.serialize(self.kernel_constraint),
<add> "bias_constraint": constraints.serialize(self.bias_constraint),
<ide> }
<ide> base_config = super(EinsumDense, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide> def _analyze_einsum_string(equation, bias_axes, input_shape, output_shape):
<ide> output_shape)
<ide>
<ide> raise ValueError(
<del> "Invalid einsum equation '%s'. Equations must be in the form "
<del> "[X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]...." % equation)
<add> f"Invalid einsum equation '{equation}'. Equations must be in the form "
<add> "[X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]....")
<ide>
<ide>
<ide> def _analyze_split_string(split_string,
<ide> def _analyze_split_string(split_string,
<ide> output_shape_at_dim != input_shape_at_dim):
<ide> raise ValueError(
<ide> "Input shape and output shape do not match at shared "
<del> "dimension '%s'. Input shape is %s, and output shape "
<del> "is %s." %
<del> (dim, input_shape_at_dim, output_shape[output_dim_map[dim]]))
<add> f"dimension '{dim}'. Input shape is {input_shape_at_dim}, "
<add> "and output shape "
<add> f"is {output_shape[output_dim_map[dim]]}.")
<ide>
<ide> for dim in output_spec:
<ide> if dim not in input_spec and dim not in weight_spec:
<del> raise ValueError("Dimension '%s' was specified in the output '%s' but "
<del> "has no corresponding dim in the input spec '%s' or "
<del> "weight spec '%s.'" % (dim, output_spec, input_spec,
<del> output_spec))
<add> raise ValueError(
<add> f"Dimension '{dim}' was specified in the output '{output_spec}' but "
<add> f"has no corresponding dim in the input spec '{input_spec}' or "
<add> f"weight spec '{output_spec}'")
<ide>
<ide> weight_shape = []
<ide> for dim in weight_spec:
<ide> def _analyze_split_string(split_string,
<ide> elif dim in output_dim_map:
<ide> weight_shape.append(output_shape[output_dim_map[dim]])
<ide> else:
<del> raise ValueError("Weight dimension '%s' did not have a match in either "
<del> "the input spec '%s' or the output spec '%s'. For this "
<del> "layer, the weight must be fully specified." %
<del> (dim, input_spec, output_spec))
<add> raise ValueError(
<add> f"Weight dimension '{dim}' did not have a match in either "
<add> f"the input spec '{input_spec}' or the output spec '{output_spec}'. "
<add> "For this layer, the weight must be fully specified.")
<ide>
<ide> if bias_axes is not None:
<ide> num_left_elided = elided if left_elided else 0
<ide> def _analyze_split_string(split_string,
<ide>
<ide> for char in bias_axes:
<ide> if char not in output_spec:
<del> raise ValueError("Bias dimension '%s' was requested, but is not a part "
<del> "of the output specification '%s'" %
<del> (char, output_spec))
<add> raise ValueError(
<add> f"Bias dimension '{char}' was requested, but is not part "
<add> f"of the output spec '{output_spec}'")
<ide>
<ide> first_bias_location = min([output_spec.find(char) for char in bias_axes])
<ide> bias_output_spec = output_spec[first_bias_location:]
<ide><path>keras/layers/einsum_dense_test.py
<ide> def test_unspecified_bias_dim_fails(self):
<ide> layer = einsum_dense.EinsumDense(
<ide> equation="ab,bc->ac", output_shape=64, bias_axes="y")
<ide> with self.assertRaisesRegex(
<del> ValueError, ".*is not a part of the output specification.*"):
<add> ValueError, ".*is not part of the output spec.*"):
<ide> _ = layer(input_tensor)
<ide>
<ide> def test_incompatible_input_output_shape_fails(self):
<ide><path>keras/layers/kernelized.py
<ide> def __init__(self,
<ide> **kwargs):
<ide> if output_dim <= 0:
<ide> raise ValueError(
<del> '`output_dim` should be a positive integer. Given: {}.'.format(
<del> output_dim))
<add> f'`output_dim` should be a positive integer. Received: {output_dim}')
<ide> if isinstance(kernel_initializer, str):
<ide> if kernel_initializer.lower() not in _SUPPORTED_RBF_KERNEL_TYPES:
<ide> raise ValueError(
<del> 'Unsupported kernel type: \'{}\'. Supported kernel types: {}.'
<del> .format(kernel_initializer, _SUPPORTED_RBF_KERNEL_TYPES))
<add> f'Unsupported `kernel_initializer`: {kernel_initializer} '
<add> f'Expected one of: {_SUPPORTED_RBF_KERNEL_TYPES}')
<ide> if scale is not None and scale <= 0.0:
<ide> raise ValueError('When provided, `scale` should be a positive float. '
<del> 'Given: {}.'.format(scale))
<add> f'Received: {scale}')
<ide> super(RandomFourierFeatures, self).__init__(
<ide> trainable=trainable, name=name, **kwargs)
<ide> self.output_dim = output_dim
<ide> def build(self, input_shape):
<ide> # to have shape [batch_size, dimension].
<ide> if input_shape.rank != 2:
<ide> raise ValueError(
<del> 'The rank of the input tensor should be 2. Got {} instead.'.format(
<del> input_shape.ndims))
<add> 'The rank of the input tensor should be 2. '
<add> f'Received input with rank {input_shape.ndims} instead. '
<add> f'Full input shape received: {input_shape}')
<ide> if input_shape.dims[1].value is None:
<ide> raise ValueError(
<del> 'The last dimension of the inputs to `RandomFourierFeatures` '
<del> 'should be defined. Found `None`.')
<add> 'The last dimension of the input tensor should be defined. '
<add> f'Found `None`. Full input shape received: {input_shape}')
<ide> self.input_spec = input_spec.InputSpec(
<ide> ndim=2, axes={1: input_shape.dims[1].value})
<ide> input_dim = input_shape.dims[1].value
<ide> def compute_output_shape(self, input_shape):
<ide> input_shape = input_shape.with_rank(2)
<ide> if input_shape.dims[-1].value is None:
<ide> raise ValueError(
<del> 'The innermost dimension of input shape must be defined. Given: %s' %
<del> input_shape)
<add> 'The last dimension of the input tensor should be defined. '
<add> f'Found `None`. Full input shape received: {input_shape}')
<ide> return input_shape[:-1].concatenate(self.output_dim)
<ide>
<ide> def get_config(self):
<ide> def _get_cauchy_samples(loc, scale, shape):
<ide>
<ide> else:
<ide> raise ValueError(
<del> 'Unsupported kernel type: \'{}\'. Supported kernel types: {}.'.format(
<del> random_features_initializer, _SUPPORTED_RBF_KERNEL_TYPES))
<add> f'Unsupported `kernel_initializer`: "{initializer}" '
<add> f'Expected one of: {_SUPPORTED_RBF_KERNEL_TYPES}')
<ide> return random_features_initializer
<ide>
<ide>
<ide><path>keras/layers/kernelized_test.py
<ide> def test_state_saving_and_loading(self):
<ide>
<ide> def test_invalid_output_dim(self):
<ide> with self.assertRaisesRegex(
<del> ValueError, r'`output_dim` should be a positive integer. Given: -3.'):
<add> ValueError, '`output_dim` should be a positive integer'):
<ide> _ = kernel_layers.RandomFourierFeatures(output_dim=-3, scale=2.0)
<ide>
<ide> def test_unsupported_kernel_type(self):
<ide> with self.assertRaisesRegex(
<del> ValueError, r'Unsupported kernel type: \'unsupported_kernel\'.'):
<add> ValueError, 'Unsupported `kernel_initializer`'):
<ide> _ = kernel_layers.RandomFourierFeatures(
<ide> 3, 'unsupported_kernel', stddev=2.0)
<ide>
<ide> def test_invalid_scale(self):
<ide> with self.assertRaisesRegex(
<ide> ValueError,
<del> r'When provided, `scale` should be a positive float. Given: 0.0.'):
<add> 'When provided, `scale` should be a positive float'):
<ide> _ = kernel_layers.RandomFourierFeatures(output_dim=10, scale=0.0)
<ide>
<ide> def test_invalid_input_shape(self):
<ide> inputs = tf.random.uniform((3, 2, 4), seed=1)
<ide> rff_layer = kernel_layers.RandomFourierFeatures(output_dim=10, scale=3.0)
<ide> with self.assertRaisesRegex(
<ide> ValueError,
<del> r'The rank of the input tensor should be 2. Got 3 instead.'):
<add> 'The rank of the input tensor should be 2'):
<ide> _ = rff_layer(inputs)
<ide>
<ide> @parameterized.named_parameters(
<ide> def test_call_on_placeholder(self, initializer):
<ide> kernel_initializer=initializer,
<ide> name='random_fourier_features')
<ide> with self.assertRaisesRegex(
<del> ValueError, r'The last dimension of the inputs to '
<del> '`RandomFourierFeatures` should be defined. Found `None`.'):
<add> ValueError,
<add> 'The last dimension of the input tensor should be defined'):
<ide> rff_layer(inputs)
<ide>
<ide> inputs = tf.compat.v1.placeholder(dtype=tf.float32, shape=[2, None])
<ide> def test_call_on_placeholder(self, initializer):
<ide> kernel_initializer=initializer,
<ide> name='random_fourier_features')
<ide> with self.assertRaisesRegex(
<del> ValueError, r'The last dimension of the inputs to '
<del> '`RandomFourierFeatures` should be defined. Found `None`.'):
<add> ValueError,
<add> 'The last dimension of the input tensor should be defined'):
<ide> rff_layer(inputs)
<ide>
<ide> inputs = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 3])
<ide> def test_compute_output_shape(self, output_dim, initializer, scale):
<ide> rff_layer.compute_output_shape(tf.TensorShape([3, 2, 3]))
<ide>
<ide> with self.assertRaisesRegex(
<del> ValueError, r'The innermost dimension of input shape must be defined.'):
<add> ValueError, 'The last dimension of the input tensor should be defined'):
<ide> rff_layer.compute_output_shape(tf.TensorShape([3, None]))
<ide>
<ide> self.assertEqual([None, output_dim],
<ide><path>keras/layers/merge.py
<ide> def _compute_elemwise_op_output_shape(self, shape1, shape2):
<ide> else:
<ide> if i != j:
<ide> raise ValueError(
<del> 'Operands could not be broadcast '
<del> 'together with shapes ' + str(shape1) + ' ' + str(shape2))
<add> 'Inputs have incompatible shapes. '
<add> f'Received shapes {shape1} and {shape2}')
<ide> output_shape.append(i)
<ide> return tuple(output_shape)
<ide>
<ide> @tf_utils.shape_type_conversion
<ide> def build(self, input_shape):
<ide> # Used purely for shape validation.
<ide> if not isinstance(input_shape[0], tuple):
<del> raise ValueError('A merge layer should be called on a list of inputs.')
<add> raise ValueError(
<add> 'A merge layer should be called on a list of inputs. '
<add> f'Received: input_shape={input_shape} (not a list of shapes)')
<ide> if len(input_shape) < 2:
<ide> raise ValueError('A merge layer should be called '
<ide> 'on a list of at least 2 inputs. '
<del> 'Got ' + str(len(input_shape)) + ' inputs.')
<add> f'Got {len(input_shape)} inputs. '
<add> f'Full input_shape received: {input_shape}')
<ide> batch_sizes = {s[0] for s in input_shape if s} - {None}
<ide> if len(batch_sizes) > 1:
<ide> raise ValueError(
<del> 'Can not merge tensors with different '
<del> 'batch sizes. Got tensors with shapes : ' + str(input_shape))
<add> 'Cannot merge tensors with different batch sizes. '
<add> f'Got tensors with shapes {input_shape}')
<ide> if input_shape[0] is None:
<ide> output_shape = None
<ide> else:
<ide> def build(self, input_shape):
<ide>
<ide> def call(self, inputs):
<ide> if not isinstance(inputs, (list, tuple)):
<del> raise ValueError('A merge layer should be called on a list of inputs.')
<add> raise ValueError(
<add> 'A merge layer should be called on a list of inputs. '
<add> f'Received: inputs={inputs} (not a list of tensors)')
<ide> if self._reshape_required:
<ide> reshaped_inputs = []
<ide> input_ndims = list(map(backend.ndim, inputs))
<ide> def compute_mask(self, inputs, mask=None):
<ide> if mask is None:
<ide> return None
<ide> if not isinstance(mask, (tuple, list)):
<del> raise ValueError('`mask` should be a list.')
<add> raise ValueError(f'`mask` should be a list. Received: mask={mask}')
<ide> if not isinstance(inputs, (tuple, list)):
<del> raise ValueError('`inputs` should be a list.')
<add> raise ValueError(f'`inputs` should be a list. Received: inputs={inputs}')
<ide> if len(mask) != len(inputs):
<del> raise ValueError('The lists `inputs` and `mask` '
<del> 'should have the same length.')
<add> raise ValueError(
<add> 'The lists `inputs` and `mask` should have the same length. '
<add> f'Received: inputs={inputs} of length {len(inputs)}, and '
<add> f'mask={mask} of length {len(mask)}')
<ide> if all(m is None for m in mask):
<ide> return None
<ide> masks = [tf.expand_dims(m, axis=0) for m in mask if m is not None]
<ide> class Subtract(_Merge):
<ide> def build(self, input_shape):
<ide> super(Subtract, self).build(input_shape)
<ide> if len(input_shape) != 2:
<del> raise ValueError('A `Subtract` layer should be called '
<del> 'on exactly 2 inputs')
<add> raise ValueError(
<add> 'A `Subtract` layer should be called on exactly 2 inputs. '
<add> f'Received: input_shape={input_shape}')
<ide>
<ide> def _merge_function(self, inputs):
<ide> if len(inputs) != 2:
<del> raise ValueError('A `Subtract` layer should be called '
<del> 'on exactly 2 inputs')
<add> raise ValueError(
<add> 'A `Subtract` layer should be called on exactly 2 inputs. '
<add> f'Received: inputs={inputs}')
<ide> return inputs[0] - inputs[1]
<ide>
<ide>
<ide> def __init__(self, axis=-1, **kwargs):
<ide> def build(self, input_shape):
<ide> # Used purely for shape validation.
<ide> if not isinstance(input_shape[0], tuple) or len(input_shape) < 1:
<del> raise ValueError('A `Concatenate` layer should be called '
<del> 'on a list of at least 1 input.')
<add> raise ValueError(
<add> 'A `Concatenate` layer should be called on a list of '
<add> f'at least 1 input. Received: input_shape={input_shape}')
<ide> if all(shape is None for shape in input_shape):
<ide> return
<ide> reduced_inputs_shapes = [list(shape) for shape in input_shape]
<ide> def build(self, input_shape):
<ide>
<ide> if len(shape_set) != 1:
<ide> err_msg = ('A `Concatenate` layer requires inputs with matching shapes '
<del> 'except for the concat axis. Got inputs shapes: %s' %
<del> input_shape)
<add> 'except for the concatenation axis. '
<add> f'Received: input_shape={input_shape}')
<ide> # Make sure all the shapes have same ranks.
<ide> ranks = set(len(shape) for shape in shape_set)
<ide> if len(ranks) != 1:
<ide> def compute_output_shape(self, input_shape):
<ide> # The tf_utils.shape_type_conversion decorator turns tensorshapes
<ide> # into tuples, so we need to verify that `input_shape` is a list/tuple,
<ide> # *and* that the individual elements are themselves shape tuples.
<del> raise ValueError('A `Concatenate` layer should be called '
<del> 'on a list of inputs.')
<add> raise ValueError(
<add> 'A `Concatenate` layer should be called on a list of inputs. '
<add> f'Received: input_shape={input_shape}')
<ide> input_shapes = input_shape
<ide> output_shape = list(input_shapes[0])
<ide> for shape in input_shapes[1:]:
<ide> def compute_mask(self, inputs, mask=None):
<ide> if mask is None:
<ide> return None
<ide> if not isinstance(mask, (tuple, list)):
<del> raise ValueError('`mask` should be a list.')
<add> raise ValueError(f'`mask` should be a list. Received mask={mask}')
<ide> if not isinstance(inputs, (tuple, list)):
<del> raise ValueError('`inputs` should be a list.')
<add> raise ValueError(f'`inputs` should be a list. Received: inputs={inputs}')
<ide> if len(mask) != len(inputs):
<del> raise ValueError('The lists `inputs` and `mask` '
<del> 'should have the same length.')
<add> raise ValueError(
<add> 'The lists `inputs` and `mask` should have the same length. '
<add> f'Received: inputs={inputs} of length {len(inputs)}, and '
<add> f'mask={mask} of length {len(mask)}')
<ide> if all(m is None for m in mask):
<ide> return None
<ide> # Make a list of masks while making sure
<ide> def __init__(self, axes, normalize=False, **kwargs):
<ide> super(Dot, self).__init__(**kwargs)
<ide> if not isinstance(axes, int):
<ide> if not isinstance(axes, (list, tuple)):
<del> raise TypeError('Invalid type for `axes` - '
<del> 'should be a list or an int.')
<add> raise TypeError(
<add> 'Invalid type for argument `axes`: it should be '
<add> f'a list or an int. Received: axes={axes}')
<ide> if len(axes) != 2:
<del> raise ValueError('Invalid format for `axes` - '
<del> 'should contain two elements.')
<add> raise ValueError(
<add> 'Invalid format for argument `axes`: it should contain two '
<add> f'elements. Received: axes={axes}')
<ide> if not isinstance(axes[0], int) or not isinstance(axes[1], int):
<del> raise ValueError('Invalid format for `axes` - '
<del> 'list elements should be "int".')
<add> raise ValueError(
<add> 'Invalid format for argument `axes`: list elements should be '
<add> f'integers. Received: axes={axes}')
<ide> self.axes = axes
<ide> self.normalize = normalize
<ide> self.supports_masking = True
<ide> def __init__(self, axes, normalize=False, **kwargs):
<ide> def build(self, input_shape):
<ide> # Used purely for shape validation.
<ide> if not isinstance(input_shape[0], tuple) or len(input_shape) != 2:
<del> raise ValueError('A `Dot` layer should be called '
<del> 'on a list of 2 inputs.')
<add> raise ValueError(
<add> 'A `Dot` layer should be called on a list of 2 inputs. '
<add> f'Received: input_shape={input_shape}')
<ide> shape1 = input_shape[0]
<ide> shape2 = input_shape[1]
<ide> if shape1 is None or shape2 is None:
<ide> def build(self, input_shape):
<ide> else:
<ide> axes = self.axes
<ide> if shape1[axes[0]] != shape2[axes[1]]:
<del> raise ValueError('Dimension incompatibility '
<del> '%s != %s. ' % (shape1[axes[0]], shape2[axes[1]]) +
<del> 'Layer shapes: %s, %s. ' % (shape1, shape2) +
<del> 'Chosen axes: %s, %s' % (axes[0], axes[1]))
<add> raise ValueError(
<add> 'Incompatible input shapes: '
<add> f'axis values {shape1[axes[0]]} (at axis {axes[0]}) != '
<add> f'{shape2[axes[1]]} (at axis {axes[1]}). '
<add> f'Full input shapes: {shape1}, {shape2}')
<ide>
<ide> def _merge_function(self, inputs):
<ide> base_layer_utils.no_ragged_support(inputs, self.name)
<ide> if len(inputs) != 2:
<del> raise ValueError('A `Dot` layer should be called on exactly 2 inputs')
<add> raise ValueError(
<add> 'A `Dot` layer should be called on exactly 2 inputs. '
<add> f'Received: inputs={inputs}')
<ide> x1 = inputs[0]
<ide> x2 = inputs[1]
<ide> if isinstance(self.axes, int):
<ide> def _merge_function(self, inputs):
<ide> @tf_utils.shape_type_conversion
<ide> def compute_output_shape(self, input_shape):
<ide> if not isinstance(input_shape, (tuple, list)) or len(input_shape) != 2:
<del> raise ValueError('A `Dot` layer should be called '
<del> 'on a list of 2 inputs.')
<add> raise ValueError(
<add> 'A `Dot` layer should be called on a list of 2 inputs. '
<add> f'Received: input_shape={input_shape}')
<ide> shape1 = list(input_shape[0])
<ide> shape2 = list(input_shape[1])
<ide> if isinstance(self.axes, int):
<ide><path>keras/layers/recurrent.py
<ide> class StackedRNNCells(Layer):
<ide>
<ide> def __init__(self, cells, **kwargs):
<ide> for cell in cells:
<del> if not 'call' in dir(cell):
<add> if 'call' not in dir(cell):
<ide> raise ValueError('All cells must have a `call` method. '
<del> 'received cells:', cells)
<del> if not 'state_size' in dir(cell):
<del> raise ValueError('All cells must have a '
<del> '`state_size` attribute. '
<del> 'received cells:', cells)
<add> f'Received cell without a `call` method: {cell}')
<add> if 'state_size' not in dir(cell):
<add> raise ValueError('All cells must have a `state_size` attribute. '
<add> f'Received cell without a `state_size`: {cell}')
<ide> self.cells = cells
<ide> # reverse_state_order determines whether the state size will be in a reverse
<ide> # order of the cells' state. User might want to set this to True to keep the
<ide> def __init__(self,
<ide> **kwargs):
<ide> if isinstance(cell, (list, tuple)):
<ide> cell = StackedRNNCells(cell)
<del> if not 'call' in dir(cell):
<del> raise ValueError('`cell` should have a `call` method. '
<del> 'The RNN was passed:', cell)
<del> if not 'state_size' in dir(cell):
<del> raise ValueError('The RNN cell should have '
<del> 'an attribute `state_size` '
<del> '(tuple of integers, '
<del> 'one integer per RNN state).')
<add> if 'call' not in dir(cell):
<add> raise ValueError('Argument `cell` should have a `call` method. '
<add> f'The RNN was passed: cell={cell}')
<add> if 'state_size' not in dir(cell):
<add> raise ValueError('The RNN cell should have a `state_size` attribute '
<add> '(tuple of integers, one integer per RNN state). '
<add> f'Received: cell={cell}')
<ide> # If True, the output for masked timestep will be zeros, whereas in the
<ide> # False case, output from previous timestep is returned for masked timestep.
<ide> self.zero_output_for_mask = kwargs.pop('zero_output_for_mask', False)
<ide> def __init__(self,
<ide>
<ide> if stateful:
<ide> if tf.distribute.has_strategy():
<del> raise ValueError('RNNs with stateful=True not yet supported with '
<del> 'tf.distribute.Strategy.')
<add> raise ValueError('Stateful RNNs (created with `stateful=True`) '
<add> 'are not yet supported with tf.distribute.Strategy.')
<ide>
<ide> @property
<ide> def _use_input_spec_as_call_signature(self):
<ide> def __call__(self, inputs, initial_state=None, constants=None, **kwargs):
<ide> flat_additional_inputs[0]) if flat_additional_inputs else True
<ide> for tensor in flat_additional_inputs:
<ide> if backend.is_keras_tensor(tensor) != is_keras_tensor:
<del> raise ValueError('The initial state or constants of an RNN'
<del> ' layer cannot be specified with a mix of'
<del> ' Keras tensors and non-Keras tensors'
<del> ' (a "Keras tensor" is a tensor that was'
<del> ' returned by a Keras layer, or by `Input`)')
<add> raise ValueError(
<add> 'The initial state or constants of an RNN layer cannot be '
<add> 'specified via a mix of Keras tensors and non-Keras tensors '
<add> '(a "Keras tensor" is a tensor that was returned by a Keras layer '
<add> ' or by `Input` during Functional model construction). '
<add> f'Received: initial_state={initial_state}, constants={constants}')
<ide>
<ide> if is_keras_tensor:
<ide> # Compute the full input spec, including state and constants
<ide> def call(self,
<ide> cell_call_fn = self.cell.__call__ if callable(self.cell) else self.cell.call
<ide> if constants:
<ide> if not generic_utils.has_arg(self.cell.call, 'constants'):
<del> raise ValueError('RNN cell does not support constants')
<add> raise ValueError(
<add> f'RNN cell {self.cell} does not support constants. '
<add> f'Received: constants={constants}')
<ide>
<ide> def step(inputs, states):
<ide> constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type
<ide> def _process_inputs(self, inputs, initial_state, constants):
<ide> initial_state = self.get_initial_state(inputs)
<ide>
<ide> if len(initial_state) != len(self.states):
<del> raise ValueError('Layer has ' + str(len(self.states)) +
<del> ' states but was passed ' + str(len(initial_state)) +
<del> ' initial states.')
<add> raise ValueError(f'Layer has {len(self.states)} '
<add> f'states but was passed {len(initial_state)} initial '
<add> f'states. Received: initial_state={initial_state}')
<ide> return inputs, initial_state, constants
<ide>
<ide> def _validate_args_if_ragged(self, is_ragged_input, mask):
<ide> if not is_ragged_input:
<ide> return
<ide>
<ide> if mask is not None:
<del> raise ValueError('The mask that was passed in was ' + str(mask) +
<del> ' and cannot be applied to RaggedTensor inputs. Please '
<del> 'make sure that there is no mask passed in by upstream '
<add> raise ValueError(f'The mask that was passed in was {mask}, which '
<add> 'cannot be applied to RaggedTensor inputs. Please '
<add> 'make sure that there is no mask injected by upstream '
<ide> 'layers.')
<ide> if self.unroll:
<ide> raise ValueError('The input received contains RaggedTensors and does '
<ide> def reset_states(self, states=None):
<ide> flat_states = tf.nest.flatten(self.states)
<ide> flat_input_states = tf.nest.flatten(states)
<ide> if len(flat_input_states) != len(flat_states):
<del> raise ValueError('Layer ' + self.name + ' expects ' +
<del> str(len(flat_states)) + ' states, '
<del> 'but it received ' + str(len(flat_input_states)) +
<del> ' state values. Input received: ' + str(states))
<add> raise ValueError(f'Layer {self.name} expects {len(flat_states)} '
<add> f'states, but it received {len(flat_input_states)} '
<add> f'state values. States received: {states}')
<ide> set_value_tuples = []
<ide> for i, (value, state) in enumerate(zip(flat_input_states,
<ide> flat_states)):
<ide> if value.shape != state.shape:
<ide> raise ValueError(
<del> 'State ' + str(i) + ' is incompatible with layer ' +
<del> self.name + ': expected shape=' + str(
<del> (batch_size, state)) + ', found shape=' + str(value.shape))
<add> f'State {i} is incompatible with layer {self.name}: '
<add> f'expected shape={(batch_size, state)} '
<add> f'but found shape={value.shape}')
<ide> set_value_tuples.append((state, value))
<ide> backend.batch_set_value(set_value_tuples)
<ide>
<ide> def call(self, inputs, states):
<ide> 1. output tensor for the current timestep, with size `output_size`.
<ide> 2. state tensor for next step, which has the shape of `state_size`.
<ide> """
<del> raise NotImplementedError('Abstract method')
<add> raise NotImplementedError
<ide>
<ide> @property
<ide> def state_size(self):
<ide> def state_size(self):
<ide> It can be represented by an Integer, a TensorShape or a tuple of Integers
<ide> or TensorShapes.
<ide> """
<del> raise NotImplementedError('Abstract method')
<add> raise NotImplementedError
<ide>
<ide> @property
<ide> def output_size(self):
<ide> """Integer or TensorShape: size of outputs produced by this cell."""
<del> raise NotImplementedError('Abstract method')
<add> raise NotImplementedError
<ide>
<ide> def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
<ide> return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype)
<ide> def __init__(self,
<ide> recurrent_dropout=0.,
<ide> **kwargs):
<ide> if units < 0:
<del> raise ValueError(f'Received an invalid value for units, expected '
<del> f'a positive integer, got {units}.')
<add> raise ValueError(f'Received an invalid value for argument `units`, '
<add> f'expected a positive integer, got {units}.')
<ide> # By default use cached variable under v2 mode, see b/143699808.
<ide> if tf.compat.v1.executing_eagerly_outside_functions():
<ide> self._enable_caching_device = kwargs.pop('enable_caching_device', True)
<ide> def __init__(self,
<ide> reset_after=False,
<ide> **kwargs):
<ide> if units < 0:
<del> raise ValueError(f'Received an invalid value for units, expected '
<del> f'a positive integer, got {units}.')
<add> raise ValueError(f'Received an invalid value for argument `units`, '
<add> f'expected a positive integer, got {units}.')
<ide> # By default use cached variable under v2 mode, see b/143699808.
<ide> if tf.compat.v1.executing_eagerly_outside_functions():
<ide> self._enable_caching_device = kwargs.pop('enable_caching_device', True)
<ide> def __init__(self,
<ide> recurrent_dropout=0.,
<ide> **kwargs):
<ide> if units < 0:
<del> raise ValueError(f'Received an invalid value for units, expected '
<del> f'a positive integer, got {units}.')
<add> raise ValueError(f'Received an invalid value for argument `units`, '
<add> f'expected a positive integer, got {units}.')
<ide> # By default use cached variable under v2 mode, see b/143699808.
<ide> if tf.compat.v1.executing_eagerly_outside_functions():
<ide> self._enable_caching_device = kwargs.pop('enable_caching_device', True)
<ide> def _generate_zero_filled_state(batch_size_tensor, state_size, dtype):
<ide> """Generate a zero filled tensor with shape [batch_size, state_size]."""
<ide> if batch_size_tensor is None or dtype is None:
<ide> raise ValueError(
<del> 'batch_size and dtype cannot be None while constructing initial state: '
<del> 'batch_size={}, dtype={}'.format(batch_size_tensor, dtype))
<add> 'batch_size and dtype cannot be None while constructing initial state. '
<add> f'Received: batch_size={batch_size_tensor}, dtype={dtype}')
<ide>
<ide> def create_zeros(unnested_state_size):
<ide> flat_dims = tf.TensorShape(unnested_state_size).as_list() | 8 |
Text | Text | add changelog entry to | 34a1c7e284e9d307f61070dfb30f0d6ab34c74d2 | <ide><path>activerecord/CHANGELOG.md
<add>* Change the schema cache format to use YAML instead of Marshal.
<add>
<add> *Kir Shatrov*
<add>
<ide> * Support index length and order options using both string and symbol
<ide> column names.
<ide> | 1 |
Ruby | Ruby | support symbol foreign key to delete | 995c697511a4e77fbe1e00793486ae07b18c5017 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def remove_foreign_key(from_table, options_or_to_table = {})
<ide> end
<ide>
<ide> fk_name_to_delete = options.fetch(:name) do
<del> fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column] }
<add> fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column].to_s }
<ide>
<ide> if fk_to_delete
<ide> fk_to_delete.name
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb
<ide> def test_remove_foreign_key_by_column
<ide> assert_equal [], @connection.foreign_keys("astronauts")
<ide> end
<ide>
<add> def test_remove_foreign_key_by_symbol_column
<add> @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id
<add>
<add> assert_equal 1, @connection.foreign_keys("astronauts").size
<add> @connection.remove_foreign_key :astronauts, column: :rocket_id
<add> assert_equal [], @connection.foreign_keys("astronauts")
<add> end
<add>
<ide> def test_remove_foreign_key_by_name
<ide> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk"
<ide> | 2 |
Go | Go | add bitseq package | 5034c9bb1154ea166be99569496df53e8fd1c62e | <ide><path>libnetwork/bitseq/sequence.go
<add>// Package bitseq provides a structure and utilities for representing long bitmask
<add>// as sequence of run-lenght encoded blocks. It operates direclty on the encoded
<add>// representation, it does not decode/encode.
<add>package bitseq
<add>
<add>import (
<add> "fmt"
<add>)
<add>
<add>// Block Sequence constants
<add>// If needed we can think of making these configurable
<add>const (
<add> blockLen = 32
<add> blockBytes = blockLen / 8
<add> blockMAX = 1<<blockLen - 1
<add> blockFirstBit = 1 << (blockLen - 1)
<add>)
<add>
<add>// Sequence reresents a recurring sequence of 32 bits long bitmasks
<add>type Sequence struct {
<add> Block uint32 // block representing 4 byte long allocation bitmask
<add> Count uint32 // number of consecutive blocks
<add> Next *Sequence // next sequence
<add>}
<add>
<add>// New returns a sequence initialized to represent a bitmaks of numElements bits
<add>func New(numElements uint32) *Sequence {
<add> return &Sequence{Block: 0x0, Count: getNumBlocks(numElements), Next: nil}
<add>}
<add>
<add>// String returns a string representation of the block sequence starting from this block
<add>func (s *Sequence) String() string {
<add> var nextBlock string
<add> if s.Next == nil {
<add> nextBlock = "end"
<add> } else {
<add> nextBlock = s.Next.String()
<add> }
<add> return fmt.Sprintf("(0x%x, %d)->%s", s.Block, s.Count, nextBlock)
<add>}
<add>
<add>// GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence
<add>func (s *Sequence) GetAvailableBit() (bytePos, bitPos int) {
<add> if s.Block == blockMAX || s.Count == 0 {
<add> return -1, -1
<add> }
<add> bits := 0
<add> bitSel := uint32(blockFirstBit)
<add> for bitSel > 0 && s.Block&bitSel != 0 {
<add> bitSel >>= 1
<add> bits++
<add> }
<add> return bits / 8, bits % 8
<add>}
<add>
<add>// Equal checks if this sequence is equal to the passed one
<add>func (s *Sequence) Equal(o *Sequence) bool {
<add> this := s
<add> other := o
<add> for this != nil {
<add> if other == nil {
<add> return false
<add> }
<add> if this.Block != other.Block || this.Count != other.Count {
<add> return false
<add> }
<add> this = this.Next
<add> other = other.Next
<add> }
<add> // Check if other is longer than this
<add> if other != nil {
<add> return false
<add> }
<add> return true
<add>}
<add>
<add>// GetFirstAvailable looks for the first unset bit in passed mask
<add>func GetFirstAvailable(head *Sequence) (int, int) {
<add> byteIndex := 0
<add> current := head
<add> for current != nil {
<add> if current.Block != blockMAX {
<add> bytePos, bitPos := current.GetAvailableBit()
<add> return byteIndex + bytePos, bitPos
<add> }
<add> byteIndex += int(current.Count * blockBytes)
<add> current = current.Next
<add> }
<add> return -1, -1
<add>}
<add>
<add>// CheckIfAvailable checks if the bit correspondent to the specified ordinal is unset
<add>// If the ordinal is beyond the Sequence limits, a negative response is returned
<add>func CheckIfAvailable(head *Sequence, ordinal int) (int, int) {
<add> bytePos := ordinal / 8
<add> bitPos := ordinal % 8
<add>
<add> // Find the Sequence containing this byte
<add> current, _, _, inBlockBytePos := findSequence(head, bytePos)
<add>
<add> if current != nil {
<add> // Check whether the bit corresponding to the ordinal address is unset
<add> bitSel := uint32(blockFirstBit >> uint(inBlockBytePos*8+bitPos))
<add> if current.Block&bitSel == 0 {
<add> return bytePos, bitPos
<add> }
<add> }
<add>
<add> return -1, -1
<add>}
<add>
<add>// Given the byte position and the sequences list head, return the pointer to the
<add>// sequence containing the byte (current), the pointer to the previous sequence,
<add>// the number of blocks preceding the block containing the byte inside the current sequence.
<add>// If bytePos is outside of the list, function will return (nil, nil, 0, -1)
<add>func findSequence(head *Sequence, bytePos int) (*Sequence, *Sequence, uint32, int) {
<add> // Find the Sequence containing this byte
<add> previous := head
<add> current := head
<add> n := bytePos
<add> for current.Next != nil && n >= int(current.Count*blockBytes) { // Nil check for less than 32 addresses masks
<add> n -= int(current.Count * blockBytes)
<add> previous = current
<add> current = current.Next
<add> }
<add>
<add> // If byte is outside of the list, let caller know
<add> if n >= int(current.Count*blockBytes) {
<add> return nil, nil, 0, -1
<add> }
<add>
<add> // Find the byte position inside the block and the number of blocks
<add> // preceding the block containing the byte inside this sequence
<add> precBlocks := uint32(n / blockBytes)
<add> inBlockBytePos := bytePos % blockBytes
<add>
<add> return current, previous, precBlocks, inBlockBytePos
<add>}
<add>
<add>// PushReservation pushes the bit reservation inside the bitmask.
<add>// Given byte and bit positions, identify the sequence (current) which holds the block containing the affected bit.
<add>// Create a new block with the modified bit according to the operation (allocate/release).
<add>// Create a new Sequence containing the new Block and insert it in the proper position.
<add>// Remove current sequence if empty.
<add>// Check if new Sequence can be merged with neighbour (previous/Next) sequences.
<add>//
<add>//
<add>// Identify "current" Sequence containing block:
<add>// [prev seq] [current seq] [Next seq]
<add>//
<add>// Based on block position, resulting list of sequences can be any of three forms:
<add>//
<add>// Block position Resulting list of sequences
<add>// A) Block is first in current: [prev seq] [new] [modified current seq] [Next seq]
<add>// B) Block is last in current: [prev seq] [modified current seq] [new] [Next seq]
<add>// C) Block is in the middle of current: [prev seq] [curr pre] [new] [curr post] [Next seq]
<add>func PushReservation(bytePos, bitPos int, head *Sequence, release bool) *Sequence {
<add> // Store list's head
<add> newHead := head
<add>
<add> // Find the Sequence containing this byte
<add> current, previous, precBlocks, inBlockBytePos := findSequence(head, bytePos)
<add> if current == nil {
<add> return newHead
<add> }
<add>
<add> // Construct updated block
<add> bitSel := uint32(blockFirstBit >> uint(inBlockBytePos*8+bitPos))
<add> newBlock := current.Block
<add> if release {
<add> newBlock &^= bitSel
<add> } else {
<add> newBlock |= bitSel
<add> }
<add>
<add> // Quit if it was a redundant request
<add> if current.Block == newBlock {
<add> return newHead
<add> }
<add>
<add> // Current Sequence inevitably looses one block, upadate Count
<add> current.Count--
<add>
<add> // Create new sequence
<add> newSequence := &Sequence{Block: newBlock, Count: 1}
<add>
<add> // Insert the new sequence in the list based on block position
<add> if precBlocks == 0 { // First in sequence (A)
<add> newSequence.Next = current
<add> if current == head {
<add> newHead = newSequence
<add> previous = newHead
<add> } else {
<add> previous.Next = newSequence
<add> }
<add> removeCurrentIfEmpty(&newHead, newSequence, current)
<add> mergeSequences(previous)
<add> } else if precBlocks == current.Count-2 { // Last in sequence (B)
<add> newSequence.Next = current.Next
<add> current.Next = newSequence
<add> mergeSequences(current)
<add> } else { // In between the sequence (C)
<add> currPre := &Sequence{Block: current.Block, Count: precBlocks, Next: newSequence}
<add> currPost := current
<add> currPost.Count -= precBlocks
<add> newSequence.Next = currPost
<add> if currPost == head {
<add> newHead = currPre
<add> } else {
<add> previous.Next = currPre
<add> }
<add> // No merging or empty current possible here
<add> }
<add>
<add> return newHead
<add>}
<add>
<add>// Removes the current sequence from the list if empty, adjusting the head pointer if needed
<add>func removeCurrentIfEmpty(head **Sequence, previous, current *Sequence) {
<add> if current.Count == 0 {
<add> if current == *head {
<add> *head = current.Next
<add> } else {
<add> previous.Next = current.Next
<add> current = current.Next
<add> }
<add> }
<add>}
<add>
<add>// Given a pointer to a Sequence, it checks if it can be merged with any following sequences
<add>// It stops when no more merging is possible.
<add>// TODO: Optimization: only attempt merge from start to end sequence, no need to scan till the end of the list
<add>func mergeSequences(seq *Sequence) {
<add> if seq != nil {
<add> // Merge all what possible from seq
<add> for seq.Next != nil && seq.Block == seq.Next.Block {
<add> seq.Count += seq.Next.Count
<add> seq.Next = seq.Next.Next
<add> }
<add> // Move to Next
<add> mergeSequences(seq.Next)
<add> }
<add>}
<add>
<add>// Serialize converts the sequence into a byte array
<add>func Serialize(head *Sequence) ([]byte, error) {
<add> return nil, nil
<add>}
<add>
<add>// Deserialize decodes the byte array into a sequence
<add>func Deserialize(data []byte) (*Sequence, error) {
<add> return nil, nil
<add>}
<add>
<add>func getNumBlocks(numBits uint32) uint32 {
<add> numBlocks := numBits / blockLen
<add> if numBits%blockLen != 0 {
<add> numBlocks++
<add> }
<add> return numBlocks
<add>}
<ide><path>libnetwork/bitseq/sequence_test.go
<add>package bitseq
<add>
<add>import (
<add> "testing"
<add>)
<add>
<add>func TestSequenceGetAvailableBit(t *testing.T) {
<add> input := []struct {
<add> head *Sequence
<add> bytePos int
<add> bitPos int
<add> }{
<add> {&Sequence{Block: 0x0, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0x0, Count: 1}, 0, 0},
<add> {&Sequence{Block: 0x0, Count: 100}, 0, 0},
<add>
<add> {&Sequence{Block: 0x80000000, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0x80000000, Count: 1}, 0, 1},
<add> {&Sequence{Block: 0x80000000, Count: 100}, 0, 1},
<add>
<add> {&Sequence{Block: 0xFF000000, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFF000000, Count: 1}, 1, 0},
<add> {&Sequence{Block: 0xFF000000, Count: 100}, 1, 0},
<add>
<add> {&Sequence{Block: 0xFF800000, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFF800000, Count: 1}, 1, 1},
<add> {&Sequence{Block: 0xFF800000, Count: 100}, 1, 1},
<add>
<add> {&Sequence{Block: 0xFFC0FF00, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFC0FF00, Count: 1}, 1, 2},
<add> {&Sequence{Block: 0xFFC0FF00, Count: 100}, 1, 2},
<add>
<add> {&Sequence{Block: 0xFFE0FF00, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFE0FF00, Count: 1}, 1, 3},
<add> {&Sequence{Block: 0xFFE0FF00, Count: 100}, 1, 3},
<add>
<add> {&Sequence{Block: 0xFFFEFF00, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFFEFF00, Count: 1}, 1, 7},
<add> {&Sequence{Block: 0xFFFEFF00, Count: 100}, 1, 7},
<add>
<add> {&Sequence{Block: 0xFFFFC0FF, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFFFC0FF, Count: 1}, 2, 2},
<add> {&Sequence{Block: 0xFFFFC0FF, Count: 100}, 2, 2},
<add>
<add> {&Sequence{Block: 0xFFFFFF00, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFFFFF00, Count: 1}, 3, 0},
<add> {&Sequence{Block: 0xFFFFFF00, Count: 100}, 3, 0},
<add>
<add> {&Sequence{Block: 0xFFFFFFFE, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFFFFFFE, Count: 1}, 3, 7},
<add> {&Sequence{Block: 0xFFFFFFFE, Count: 100}, 3, 7},
<add>
<add> {&Sequence{Block: 0xFFFFFFFF, Count: 0}, -1, -1},
<add> {&Sequence{Block: 0xFFFFFFFF, Count: 1}, -1, -1},
<add> {&Sequence{Block: 0xFFFFFFFF, Count: 100}, -1, -1},
<add> }
<add>
<add> for n, i := range input {
<add> b, bb := i.head.GetAvailableBit()
<add> if b != i.bytePos || bb != i.bitPos {
<add> t.Fatalf("Error in Sequence.getAvailableBit() (%d).\nExp: (%d, %d)\nGot: (%d, %d),", n, i.bytePos, i.bitPos, b, bb)
<add> }
<add> }
<add>}
<add>
<add>func TestSequenceEqual(t *testing.T) {
<add> input := []struct {
<add> first *Sequence
<add> second *Sequence
<add> areEqual bool
<add> }{
<add> {&Sequence{Block: 0x0, Count: 8, Next: nil}, &Sequence{Block: 0x0, Count: 8}, true},
<add> {&Sequence{Block: 0x0, Count: 0, Next: nil}, &Sequence{Block: 0x0, Count: 0}, true},
<add> {&Sequence{Block: 0x0, Count: 2, Next: nil}, &Sequence{Block: 0x0, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}, false},
<add> {&Sequence{Block: 0x0, Count: 2, Next: &Sequence{Block: 0x1, Count: 1}}, &Sequence{Block: 0x0, Count: 2}, false},
<add>
<add> {&Sequence{Block: 0x12345678, Count: 8, Next: nil}, &Sequence{Block: 0x12345678, Count: 8}, true},
<add> {&Sequence{Block: 0x12345678, Count: 8, Next: nil}, &Sequence{Block: 0x12345678, Count: 9}, false},
<add> {&Sequence{Block: 0x12345678, Count: 1, Next: &Sequence{Block: 0XFFFFFFFF, Count: 1}}, &Sequence{Block: 0x12345678, Count: 1}, false},
<add> {&Sequence{Block: 0x12345678, Count: 1}, &Sequence{Block: 0x12345678, Count: 1, Next: &Sequence{Block: 0XFFFFFFFF, Count: 1}}, false},
<add> }
<add>
<add> for n, i := range input {
<add> if i.areEqual != i.first.Equal(i.second) {
<add> t.Fatalf("Error in Sequence.Equal() (%d).\nExp: %t\nGot: %t,", n, i.areEqual, !i.areEqual)
<add> }
<add> }
<add>}
<add>
<add>func TestGetFirstAvailable(t *testing.T) {
<add> input := []struct {
<add> mask *Sequence
<add> bytePos int
<add> bitPos int
<add> }{
<add> {&Sequence{Block: 0xffffffff, Count: 2048}, -1, -1},
<add> {&Sequence{Block: 0x0, Count: 8}, 0, 0},
<add> {&Sequence{Block: 0x80000000, Count: 8}, 0, 1},
<add> {&Sequence{Block: 0xC0000000, Count: 8}, 0, 2},
<add> {&Sequence{Block: 0xE0000000, Count: 8}, 0, 3},
<add> {&Sequence{Block: 0xF0000000, Count: 8}, 0, 4},
<add> {&Sequence{Block: 0xF8000000, Count: 8}, 0, 5},
<add> {&Sequence{Block: 0xFC000000, Count: 8}, 0, 6},
<add> {&Sequence{Block: 0xFE000000, Count: 8}, 0, 7},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x00000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 2},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xE0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 3},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 4},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF8000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 5},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFC000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 6},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFE000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 7},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF800000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFC00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 2},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFE00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 3},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 4},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF80000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 5},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFC0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 6},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFE0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 7},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 7, 7},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 2, Next: &Sequence{Block: 0x0, Count: 6}}, 8, 0},
<add> }
<add>
<add> for n, i := range input {
<add> bytePos, bitPos := GetFirstAvailable(i.mask)
<add> if bytePos != i.bytePos || bitPos != i.bitPos {
<add> t.Fatalf("Error in (%d) getFirstAvailable(). Expected (%d, %d). Got (%d, %d)", n, i.bytePos, i.bitPos, bytePos, bitPos)
<add> }
<add> }
<add>}
<add>
<add>func TestFindSequence(t *testing.T) {
<add> input := []struct {
<add> head *Sequence
<add> bytePos int
<add> precBlocks uint32
<add> inBlockBytePos int
<add> }{
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 0, 0, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 31, 0, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 100, 0, -1},
<add>
<add> {&Sequence{Block: 0x0, Count: 1}, 0, 0, 0},
<add> {&Sequence{Block: 0x0, Count: 1}, 1, 0, 1},
<add> {&Sequence{Block: 0x0, Count: 1}, 31, 0, -1},
<add> {&Sequence{Block: 0x0, Count: 1}, 60, 0, -1},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 0, 0, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 3, 0, 3},
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 4, 1, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 7, 1, 3},
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 8, 2, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 10}, 39, 9, 3},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 10, Next: &Sequence{Block: 0xcc000000, Count: 10}}, 79, 9, 3},
<add> {&Sequence{Block: 0xffffffff, Count: 10, Next: &Sequence{Block: 0xcc000000, Count: 10}}, 80, 0, -1},
<add> }
<add>
<add> for n, i := range input {
<add> _, _, precBlocks, inBlockBytePos := findSequence(i.head, i.bytePos)
<add> if precBlocks != i.precBlocks || inBlockBytePos != i.inBlockBytePos {
<add> t.Fatalf("Error in (%d) findSequence(). Expected (%d, %d). Got (%d, %d)", n, i.precBlocks, i.inBlockBytePos, precBlocks, inBlockBytePos)
<add> }
<add> }
<add>}
<add>
<add>func TestCheckIfAvailable(t *testing.T) {
<add> input := []struct {
<add> head *Sequence
<add> ordinal int
<add> bytePos int
<add> bitPos int
<add> }{
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 0, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 31, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 0}, 100, -1, -1},
<add>
<add> {&Sequence{Block: 0x0, Count: 1}, 0, 0, 0},
<add> {&Sequence{Block: 0x0, Count: 1}, 1, 0, 1},
<add> {&Sequence{Block: 0x0, Count: 1}, 31, 3, 7},
<add> {&Sequence{Block: 0x0, Count: 1}, 60, -1, -1},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x800000ff, Count: 1}}, 31, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x800000ff, Count: 1}}, 32, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x800000ff, Count: 1}}, 33, 4, 1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1}}, 33, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1}}, 34, 4, 2},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 55, 6, 7},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 56, -1, -1},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 63, -1, -1},
<add>
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 64, 8, 0},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 95, 11, 7},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC00000ff, Count: 1, Next: &Sequence{Block: 0x0, Count: 1}}}, 96, -1, -1},
<add> }
<add>
<add> for n, i := range input {
<add> bytePos, bitPos := CheckIfAvailable(i.head, i.ordinal)
<add> if bytePos != i.bytePos || bitPos != i.bitPos {
<add> t.Fatalf("Error in (%d) checkIfAvailable(ord:%d). Expected (%d, %d). Got (%d, %d)", n, i.ordinal, i.bytePos, i.bitPos, bytePos, bitPos)
<add> }
<add> }
<add>}
<add>
<add>func TestMergeSequences(t *testing.T) {
<add> input := []struct {
<add> original *Sequence
<add> merged *Sequence
<add> }{
<add> {&Sequence{Block: 0xFE000000, Count: 8, Next: &Sequence{Block: 0xFE000000, Count: 2}}, &Sequence{Block: 0xFE000000, Count: 10}},
<add> {&Sequence{Block: 0xFFFFFFFF, Count: 8, Next: &Sequence{Block: 0xFFFFFFFF, Count: 1}}, &Sequence{Block: 0xFFFFFFFF, Count: 9}},
<add> {&Sequence{Block: 0xFFFFFFFF, Count: 1, Next: &Sequence{Block: 0xFFFFFFFF, Count: 8}}, &Sequence{Block: 0xFFFFFFFF, Count: 9}},
<add>
<add> {&Sequence{Block: 0xFFFFFFF0, Count: 8, Next: &Sequence{Block: 0xFFFFFFF0, Count: 1}}, &Sequence{Block: 0xFFFFFFF0, Count: 9}},
<add> {&Sequence{Block: 0xFFFFFFF0, Count: 1, Next: &Sequence{Block: 0xFFFFFFF0, Count: 8}}, &Sequence{Block: 0xFFFFFFF0, Count: 9}},
<add>
<add> {&Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xFE, Count: 1, Next: &Sequence{Block: 0xFE, Count: 5}}}, &Sequence{Block: 0xFE, Count: 14}},
<add> {&Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xFE, Count: 1, Next: &Sequence{Block: 0xFE, Count: 5, Next: &Sequence{Block: 0xFF, Count: 1}}}},
<add> &Sequence{Block: 0xFE, Count: 14, Next: &Sequence{Block: 0xFF, Count: 1}}},
<add>
<add> // No merge
<add> {&Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xF8, Count: 1, Next: &Sequence{Block: 0xFE, Count: 5}}},
<add> &Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xF8, Count: 1, Next: &Sequence{Block: 0xFE, Count: 5}}}},
<add>
<add> // No merge from head: // Merge function tries to merge from passed head. If it can't merge with Next, it does not reattempt with Next as head
<add> {&Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xFF, Count: 1, Next: &Sequence{Block: 0xFF, Count: 5}}},
<add> &Sequence{Block: 0xFE, Count: 8, Next: &Sequence{Block: 0xFF, Count: 6}}},
<add> }
<add>
<add> for n, i := range input {
<add> mergeSequences(i.original)
<add> for !i.merged.Equal(i.original) {
<add> t.Fatalf("Error in (%d) mergeSequences().\nExp: %s\nGot: %s,", n, i.merged, i.original)
<add> }
<add> }
<add>}
<add>
<add>func TestPushReservation(t *testing.T) {
<add> input := []struct {
<add> mask *Sequence
<add> bytePos int
<add> bitPos int
<add> newMask *Sequence
<add> }{
<add> // Create first Sequence and fill in 8 addresses starting from address 0
<add> {&Sequence{Block: 0x0, Count: 8, Next: nil}, 0, 0, &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0x80000000, Count: 8}, 0, 1, &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0x80000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xC0000000, Count: 8}, 0, 2, &Sequence{Block: 0xE0000000, Count: 1, Next: &Sequence{Block: 0xC0000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xE0000000, Count: 8}, 0, 3, &Sequence{Block: 0xF0000000, Count: 1, Next: &Sequence{Block: 0xE0000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xF0000000, Count: 8}, 0, 4, &Sequence{Block: 0xF8000000, Count: 1, Next: &Sequence{Block: 0xF0000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xF8000000, Count: 8}, 0, 5, &Sequence{Block: 0xFC000000, Count: 1, Next: &Sequence{Block: 0xF8000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xFC000000, Count: 8}, 0, 6, &Sequence{Block: 0xFE000000, Count: 1, Next: &Sequence{Block: 0xFC000000, Count: 7, Next: nil}}},
<add> {&Sequence{Block: 0xFE000000, Count: 8}, 0, 7, &Sequence{Block: 0xFF000000, Count: 1, Next: &Sequence{Block: 0xFE000000, Count: 7, Next: nil}}},
<add>
<add> {&Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 7}}, 0, 1, &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 7, Next: nil}}},
<add>
<add> // Create second Sequence and fill in 8 addresses starting from address 32
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x00000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6, Next: nil}}}, 4, 0,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 1,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 2,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xE0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xE0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 3,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF0000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 4,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF8000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xF8000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 5,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFC000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFC000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 6,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFE000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFE000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 4, 7,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> // fill in 8 addresses starting from address 40
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF000000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 0,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF800000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFF800000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 1,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFC00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFC00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 2,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFE00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFE00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 3,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF00000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 4,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF80000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFF80000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 5,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFC0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFC0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 6,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFE0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFE0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}, 5, 7,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xFFFF0000, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 6}}}},
<add>
<add> // Insert new Sequence
<add> {&Sequence{Block: 0xffffffff, Count: 2, Next: &Sequence{Block: 0x0, Count: 6}}, 8, 0,
<add> &Sequence{Block: 0xffffffff, Count: 2, Next: &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 5}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 2, Next: &Sequence{Block: 0x80000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 5}}}, 8, 1,
<add> &Sequence{Block: 0xffffffff, Count: 2, Next: &Sequence{Block: 0xC0000000, Count: 1, Next: &Sequence{Block: 0x0, Count: 5}}}},
<add>
<add> // Merge affected with Next
<add> {&Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 2, Next: &Sequence{Block: 0xffffffff, Count: 1}}}, 31, 7,
<add> &Sequence{Block: 0xffffffff, Count: 8, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 1}}}},
<add> {&Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xfffffffc, Count: 1, Next: &Sequence{Block: 0xfffffffe, Count: 6}}}, 7, 6,
<add> &Sequence{Block: 0xffffffff, Count: 1, Next: &Sequence{Block: 0xfffffffe, Count: 7}}},
<add>
<add> // Merge affected with Next and Next.Next
<add> {&Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 1}}}, 31, 7,
<add> &Sequence{Block: 0xffffffff, Count: 9}},
<add> {&Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 1}}, 31, 7,
<add> &Sequence{Block: 0xffffffff, Count: 8}},
<add>
<add> // Merge affected with previous and Next
<add> {&Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 1}}}, 31, 7,
<add> &Sequence{Block: 0xffffffff, Count: 9}},
<add>
<add> // Redundant push: No change
<add> {&Sequence{Block: 0xffff0000, Count: 1}, 0, 0, &Sequence{Block: 0xffff0000, Count: 1}},
<add> {&Sequence{Block: 0xffff0000, Count: 7}, 25, 7, &Sequence{Block: 0xffff0000, Count: 7}},
<add> {&Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 1}}}, 7, 7,
<add> &Sequence{Block: 0xffffffff, Count: 7, Next: &Sequence{Block: 0xfffffffe, Count: 1, Next: &Sequence{Block: 0xffffffff, Count: 1}}}},
<add> }
<add>
<add> for n, i := range input {
<add> mask := PushReservation(i.bytePos, i.bitPos, i.mask, false)
<add> if !mask.Equal(i.newMask) {
<add> t.Fatalf("Error in (%d) pushReservation():\n%s + (%d,%d):\nExp: %s\nGot: %s,", n, i.mask, i.bytePos, i.bitPos, i.newMask, mask)
<add> }
<add> }
<add>} | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.